我有一个充满单词及其属性的数据框,其中一列标题为"拼写"。这包含每个单词的拼写,每个字符用空格分隔,如下所示:
P L A T E
米·阿特
罗奥克·
我有一个单独的字符向量,其中包含被认为对分析很重要的字母子集。喜欢这个:
important_letters <- c("P","M","E")
我需要编写一个函数,对于数据帧中的每一行,计算单词中包含多少个字符的重要字母,并在数据框中使用此数字创建一个新列。在此示例中,新列将包含 2 表示板、1 表示垫子和 0 表示岩石。
我一直在试图弄清楚这一点,我知道函数的返回行应该是这样的:
return(sum(a %in% important_letters))
任何帮助将不胜感激。
试试这个:
library(dplyr)
# your objects
Spelling <- c('P L A T E', 'M A T', 'R O C K')
important_letters <- c("P","M","E")
df <- data.frame(Spelling, stringsAsFactors = FALSE)
# first, create a new variable (field) in dataframe
df$important_letters_count <- NA
# this is the function
count_important <- function(x) {
for (i in 1:nrow(x)) {
x$important_letters_count[i] <-
sum(strsplit(x$Spelling[i], " ")[[1]] %in% important_letters)
}
x
}
# call the functions this way
df <- count_important(df)
另一种选择:
sum_letters <- function(words, imp_letters) {
sapply(words,
function(x) sum(unlist(strsplit(x, split = " ")) %in% imp_letters, na.rm = TRUE)
)
}
可以这样称呼:
df$sum_letters <- sum_letters(df$words, important_letters)
输出:
df
words sum_letters
1 P L A T E 2
2 M A T 1
3 R O C K 0
使用 purrr
和 stringr
。map
派生遍历字符向量,并将自定义函数应用于每个元素。使用str_count
来计算重要字母的匹配项。
library(stringr)
library(purrr)
df <- data.frame(
Spelling = c("P L A T E", "M A T", "R O C K")
)
important_letters <- c("P", "M", "E")
map_dbl(df$Spelling, ~ sum(str_count(.x, important_letters)))
试试这个:
myfunc <- function(v, imp) {
ptn <- paste0(c("[^", imp, "]"), collapse = "")
nchar(gsub(ptn, "", v))
}
# sample data
vec <- c("P L A T E", "M A T", "R O C K")
important_letters <- c("P","M","E")
myfunc(vec, important_letters)
# [1] 2 1 0
因为它是在这里的向量上运行的,所以它可以很容易地迭代帧列。