如何根据 R 中的另一列值为一列赋值?

How to assign a value for a column based on another column value in R?

我有一个数据框

 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")]

这可行,但我认为有更好的方法。 谢谢!

可能有帮助

df$col4 <- paste0("newValue_", cumsum(!duplicated(df$col2)))
df$col4
#[1] "newValue_1" "newValue_1" "newValue_1" "newValue_1" "newValue_2"

或者我们用match

with(df, paste0("newValue_", match(col2, unique(col2))))
#[1] "newValue_1" "newValue_1" "newValue_1" "newValue_1" "newValue_2"

或者可以用factor

来完成
with(df, paste0("newValue_", as.integer(factor(col2, levels = unique(col2)))))

您可以尝试 dense_rank() 来自 dplyr:

library(dplyr)
df %>% 
    mutate(col4 = dense_rank(col2),
           col4_new = paste0("newValue_", col4))

这给出了与您在问题中所需的输出非常相似的内容,但我不确定您在寻找什么。如果您想确保 所有 行在 col2 中具有相同值的行在 col4 中获得相同的值那么只需 arrange df然后使用 dense_rank :

df %>% 
    arrange(col2) %>% 
    mutate(col4 = dense_rank(col2),
           col4_new = paste0("newValue_", col4))

这应该适用于任意大小的 data.frame