如何处理数据框中含向量的value列并计算各word的均值?
Solution for Converting Value Column and Calculating Means
First, let's recreate your data frame in R (assuming the value column is stored as character strings):
# Create the sample data frame df <- data.frame( word = c("a", "b", "c", "d", "e", "f"), value = c("3", "c(1, 10, 15, 17)", "8", "c(2,9)", "c(3, 7, 8, 12, 16, 17, 19)", "6"), stringsAsFactors = FALSE )
Step 1: Convert value column to numeric vectors
Use lapply() to evaluate each string as an R expression, turning them into actual numeric vectors:
# Convert character strings to numeric vectors df$value <- lapply(df$value, function(x) eval(parse(text = x)))
Now, the value column contains numeric vectors (scalars for single values, multi-element vectors for the c(...) entries).
Step 2: Calculate the mean for each word
Use sapply() to compute the mean of each vector in the value column:
# Compute mean for each row df$mean <- sapply(df$value, mean)
Final Result
Your data frame will now include the mean for each word:
print(df) # word value mean # 1 a 3 3.000000 # 2 b 1, 10, 15, 17 10.750000 # 3 c 8 8.000000 # 4 d 2, 9 5.500000 # 5 e 3, 7, 8, 12, 16, 17, 19 11.714286 # 6 f 6 6.000000
Notes
- This approach assumes all entries in the
valuecolumn are valid R numeric expressions (either single numbers orc(...)vectors). If there are invalid entries, add error handling withtryCatch()to avoid crashes. eval(parse(...))works here because your entries follow valid R syntax, but avoid using this with untrusted input as it can execute arbitrary code.
内容的提问来源于stack exchange,提问作者user21390049
相关产品推荐
相关产品推荐

