R中的填充系列

时间:2018-07-03 13:30:57

标签: r loops series fill

我想更新第2列,以便值对更新为(a,1)(b,1)(c1)和(d,2)(e,2)(f,2)和(g, 3)(h,3)(i,3)等。我如何循环? 这是示例数据帧:

data_set <- as.data.frame(matrix(nrow=9))
data_set$column1_set1 <- c("a","b","c","d","e","f","g","h","i")
data_set$column2_set1 <- c(0,0,0,0,0,0,0,0,0)

data_set <- data_set[,-1]

2 个答案:

答案 0 :(得分:3)

data_set <- data.frame(column1_set1 = letters[1:9], 
                       column2_set1 = rep(1:3, each=3))

答案 1 :(得分:1)

使用给定的数据集,您可以使用它来成对更新第2列:a,1等 将逗号粘贴到set1中,并重复1:3,每次= 3次!

data_set$column2_set1 =paste0(data_set$column1_set1,",",rep(1:3, each=3))

=== 您也可以在dplyr中使用mutate:

data_set%>%
  mutate("column2_set1" = paste0(column1_set1,",",rep(1:3, each=3)))

输出: column1_set1 column2_set1 1 a a,1 2 b b,1 3 c c,1 4 d d,2 5 e e,2 6 f f,2 7 g g,3 8 h h,3 9 i i,3