我有一个数据框
df <- data.frame(structure(list(col1= c("A", "B", "C", "D", "A"),
col2= c(1, 1, 1, 1, 5), col3 = c(2L, 1L, 1L, 1L, 1L)),
.Names = c("col1", "col2", "col3"),
row.names = c(NA, -5L), class = "data.frame"))
我想添加附加列 col4,其值基于 col2。在 col2 中具有相同值的行在 col4 中也将具有相同的值。
通过解决方法,我通过以下方式生成了结果。
x <- df[!duplicated(df$col2),]
x$col4 <- paste("newValue", seq(1:nrow(x)), sep="_")
df_new <- merge(x, df, by ="col2")
df_new <- df_new[,c("col2","col4", "col1.y", "col3.y")]
这可行,但我认为有更好的方法来做到这一点。谢谢!