R 将两个或多个列添加到一个具有sum的列中
输入数据结构R 将两个或多个列添加到一个具有sum的列中,r,R,输入数据结构 data.frame(id = c(1,2,3), name = c(0,1,0) col = c(1,1,0), another = c(1,2,0)) 什么样的命令可以添加两个(或更多)列并创建一个新列,其中总和大于一个add 1 下面是一个示例结果,添加名为name和col from df的列,并创建名为combine的新列: data.frame(id = c(1,2,3), combine = c(1,1,0), another = c(1,2,0)) 使用行和 c.
data.frame(id = c(1,2,3), name = c(0,1,0) col = c(1,1,0), another = c(1,2,0))
什么样的命令可以添加两个(或更多)列并创建一个新列,其中总和大于一个add 1
下面是一个示例结果,添加名为name和col from df的列,并创建名为combine的新列:
data.frame(id = c(1,2,3), combine = c(1,1,0), another = c(1,2,0))
使用
行和
c.col <- c("name", "col")
res <- data.frame(combine=+(rowSums(d[c.col]) > 0), d[!names(d) %in% c.col])
res
# combine id another
# 1 1 1 1
# 2 1 2 2
# 3 0 3 0
res <- res[c(2, 1, 3)] ## order columns if needed
# id combine another
# 1 1 1 1
# 2 2 1 2
# 3 3 0 0
c.col Tryas.integer(行和(d1[c('name','col'))>0)
谢谢,是否可以使用列的名称而不是数据框中的位置?
d <- structure(list(id = c(1, 2, 3), name = c(0, 1, 0), col = c(1,
1, 0), another = c(1, 2, 0)), class = "data.frame", row.names = c(NA,
-3L))