将增量数字附加到列中的特定字符串
Append incremental number to specific string in a column
我确定这是一些基本的东西,但我就是找不到合适的解决方案。
我有一个很大的 df,看起来像:
Sample cat
data1 124
data2 125
data3 126
Test1 Nice
Test2 Fluffy
Sample Dog
data1 123
data2 124
data3 125
Test1 Good
Test2 Soft
我想将增量数字添加到第一列中的 Sample
值,这样我会得到以下输出:
Sample_1 cat
data1 124
data2 125
data3 126
Test1 Nice
Test2 Fluffy
Sample_2 Dog
data1 123
data2 124
data3 125
Test1 Good
Test2 Soft
我尝试了各种 gsub、grep、paste、paste0 组合,但都不满意。
例子
structure(list(V1 = c("Sample", "data1", "data2", "data3", "Test1", "Test2", "Sample", "data1", "data2", "data3", "Test1", "Test2"), V2 = structure(c(5L, 2L, 3L, 4L, 9L, 7L, 6L, 1L, 2L, 3L, 8L, 10L), .Label = c("123", "124", "125", "126", "cat", "Dog", "Fluffy", "Good", "Nice", "Soft"), class = "factor")), row.names = c(NA, -12L), class = "data.frame")
您可以使用 cumsum
来获取 Samples
和 paste
的数量,即
d1$V1[d1$V1 == 'Sample'] <- paste0(d1$V1[d1$V1 == 'Sample'], '_', unique(cumsum(d1$V1 == 'Sample')))
像这样的东西应该有用...
df2 <- df %>%
filter(str_detect(V1, "Sample")) %>%
mutate(V1 = ifelse(str_detect(V1, "Sample"), paste0("Sample_", row_number()), V1))
df <- df[-which(df$V1 == "Sample"),]
rbind(df2, df)
-布伦南
我确定这是一些基本的东西,但我就是找不到合适的解决方案。 我有一个很大的 df,看起来像:
Sample cat
data1 124
data2 125
data3 126
Test1 Nice
Test2 Fluffy
Sample Dog
data1 123
data2 124
data3 125
Test1 Good
Test2 Soft
我想将增量数字添加到第一列中的 Sample
值,这样我会得到以下输出:
Sample_1 cat
data1 124
data2 125
data3 126
Test1 Nice
Test2 Fluffy
Sample_2 Dog
data1 123
data2 124
data3 125
Test1 Good
Test2 Soft
我尝试了各种 gsub、grep、paste、paste0 组合,但都不满意。
例子
structure(list(V1 = c("Sample", "data1", "data2", "data3", "Test1", "Test2", "Sample", "data1", "data2", "data3", "Test1", "Test2"), V2 = structure(c(5L, 2L, 3L, 4L, 9L, 7L, 6L, 1L, 2L, 3L, 8L, 10L), .Label = c("123", "124", "125", "126", "cat", "Dog", "Fluffy", "Good", "Nice", "Soft"), class = "factor")), row.names = c(NA, -12L), class = "data.frame")
您可以使用 cumsum
来获取 Samples
和 paste
的数量,即
d1$V1[d1$V1 == 'Sample'] <- paste0(d1$V1[d1$V1 == 'Sample'], '_', unique(cumsum(d1$V1 == 'Sample')))
像这样的东西应该有用...
df2 <- df %>%
filter(str_detect(V1, "Sample")) %>%
mutate(V1 = ifelse(str_detect(V1, "Sample"), paste0("Sample_", row_number()), V1))
df <- df[-which(df$V1 == "Sample"),]
rbind(df2, df)
-布伦南