【发布时间】:2020-08-27 13:05:30
【问题描述】:
我目前编写了这段代码来计算代码的第一个字母出现在表格的特定列中的次数。
#a test data frame
test <- data.frame("State" = c("PA", "RI", "SC"), "Code1" = c("EFGG, AFGG", "SSAG", "AFGG, SSAG"))
#code to count method codes
test[] <- lapply(test, as.character)
test_counts <- sapply(strsplit(test$Code1, ",\\s+"), function(x) {
tab <- table(substr(x, 1, 1)) # Create a table of the first letters
paste0(names(tab), tab, collapse = ", ") # Paste together the letter w/ the number and collapse
them
} )
#example of output
[1] "A1, E1" "S1" "A1, S1"
关于当前代码的一切都是完美的,除了我希望 R 不按字母顺序输出计数。我希望它保留代码的顺序。所以这就是我希望输出的样子:
[1] "E1, A1", "S1", "A1, S1"
谢谢!!
【问题讨论】:
标签: r string count strsplit preserve