我有一个观察两种蜗牛寄生虫的数据集,我想要创建一个新的列,说明蜗牛是否没有寄生虫“无”,类型1 "TYPE1",类型2 "TYPE2“,还是两种寄生虫”双重“。
Block Weight Parasite1 Parasite2
1 1 1.23 1 1
2 1 3.14 1 1
3 1 2.55 1 0
4 1 2.67 0 1
5 1 3.36 0 1
6 1 3.16 0 0
7 1 3.41 0 1
8 1 2.47 0 1
9 1 1.56 0 1
10 1 2.66 1 1我曾经想过如果或者如果其他的话,但我似乎不能让它工作?
发布于 2014-11-19 15:38:30
你可以用一些如果其他语句,但这更容易我认为
dat <- read.table(header = TRUE, text="row Block Weight Parasite1 Parasite2
1 1 1.23 1 1
2 1 3.14 1 1
3 1 2.55 1 0
4 1 2.67 0 1
5 1 3.36 0 1
6 1 3.16 0 0
7 1 3.41 0 1
8 1 2.47 0 1
9 1 1.56 0 1
10 1 2.66 1 1")[,-1]
within(dat, {
type <- interaction(Parasite1, Parasite2, sep = '')
type <- factor(type, levels = c('11','10','01','00'),
labels = c('DUAL','TYPE1','TYPE2','None'))
})
# Block Weight Parasite1 Parasite2 type
# 1 1 1.23 1 1 DUAL
# 2 1 3.14 1 1 DUAL
# 3 1 2.55 1 0 TYPE1
# 4 1 2.67 0 1 TYPE2
# 5 1 3.36 0 1 TYPE2
# 6 1 3.16 0 0 None
# 7 1 3.41 0 1 TYPE2
# 8 1 2.47 0 1 TYPE2
# 9 1 1.56 0 1 TYPE2
# 10 1 2.66 1 1 DUAL发布于 2014-11-19 15:41:38
你可以试试
df$NewCol <- c('None', 'TYPE1', 'TYPE2', 'DUAL')[with(df,
as.numeric(factor(1+2*Parasite1+4*Parasite2)))]
df
# Block Weight Parasite1 Parasite2 NewCol
#1 1 1.23 1 1 DUAL
#2 1 3.14 1 1 DUAL
#3 1 2.55 1 0 TYPE1
#4 1 2.67 0 1 TYPE2
#5 1 3.36 0 1 TYPE2
#6 1 3.16 0 0 None
#7 1 3.41 0 1 TYPE2
#8 1 2.47 0 1 TYPE2
#9 1 1.56 0 1 TYPE2
#10 1 2.66 1 1 DUAL数据
df <- structure(list(Block = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L), Weight = c(1.23, 3.14, 2.55, 2.67, 3.36, 3.16, 3.41, 2.47,
1.56, 2.66), Parasite1 = c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
1L), Parasite2 = c(1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L)), .Names = c("Block",
"Weight", "Parasite1", "Parasite2"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))https://stackoverflow.com/questions/27020610
复制相似问题