作为输入,我们具有以下数据结构:
dframe <- data.frame(id = c(1,2,3), col1 = c(4.2, 1.2,0), su = c(1.2,2.4,0))
创建新列的代码
com_num <- with(dframe, pmax(col1, su))
i <- which(dframe[-1] == com_num, arr.ind = TRUE)
dframe$com <- names(dframe[-1])[i[, 2]]
dframe$com_num <- com_num
但是这个错误存在
Error in `$<-.data.frame`(`*tmp*`, com, value = c("col1", "col1", "su", :
replacement has 4 rows, data has 3
我认为这是因为零等于零。如果是这种情况,当检测到零等于零时如何添加文本“ zerohere”?
预期输出:
> dframe <- data.frame(id = c(1,2,3), col1 = c(4.2, 1.2,0), su = c(1.2,2.4,0), com = c("col1","su","zerohere"), com_num = c(4.2,2.4,0))
> dframe
id col1 su com com_num
1 1 4.2 1.2 col1 4.2
2 2 1.2 2.4 su 2.4
3 3 0.0 0.0 zerohere 0.0