1

我有一个数据框

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

这可行,但我认为有更好的方法来做到这一点。谢谢!

4

2 回答 2

2

您可以尝试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任意大小。

于 2016-08-12T10:08:49.827 回答
1

可能这有帮助

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)))))
于 2016-08-12T09:55:13.053 回答