我有一个数据框(df
),如下所示:
gene times.x times.y times.z
AC113084.1 1 NA 0
AC124108.15-1 0 5 3
AC154871.1 NA NA 12
我要做的是创建一个新列df$new
,我将根据列时间(x.y.z)的不同组合命名,如下所示:
gene times.x times.y times.z new
AC113084.1 1 NA 0 located.up
AC124108.15-1 0 5 3 located.down
AC154871.1 NA NA 12 not.located
请您给我一些建议如何让该列分配这些特征(例如我想打印以下内容):
如果located.up
,则new
列中的 times.x>1 & times.y=NA & times.z=0
如果located.down
new
列中的 times.x=0 & times.y>1 & times.z>1
如果not.located
new
列中的 times.x=NA & times.y=NA & times.z>1
答案 0 :(得分:3)
以下是根据您的规则创建新列的一种方法:
ix1 <- df$times.x > 1
iyn <- is.na(df$times.y)
iz0 <- !df$times.z
ix0 <- !df$times.x
iy1 <- df$times.y > 1
iz1 <- df$times.z > 1
ixn <- is.na(df$times.x)
# new vector
newCol <- character(nrow(df))
# replace values in vector
newCol[ix1 & iyn & iz0] <- "located.up"
newCol[ix0 & iy1 & iz1] <- "located.down"
newCol[ixn & iyn & iz1] <- "not.located"
# add to data frame
df$new <- newCol
结果:
gene times.x times.y times.z new
1 AC113084.1 1 NA 0
2 AC124108.15-1 0 5 3 located.down
3 AC154871.1 NA NA 12 not.located
请注意,我遵守了您的规则。因此,获得的第一行输出与您的示例不匹配。
答案 1 :(得分:2)
您可以创建嵌套的ifelse
语句,例如:
df$new <-
ifelse(df$times.x>1 & is.na(df$times.y) & df$times.z==0,
"located.up",
ifelse(df$times.x==0 & df$times.y>1 & df$times.z>1,
"located.down",
ifelse(is.na(df$times.x) & is.na(df$times.y) & df$times.z>1,
"not.located",NA)))
答案 2 :(得分:1)
您可以gene$new <-
&#34;构建if和else语句&#34;。