You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理数据框中含向量的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 value column are valid R numeric expressions (either single numbers or c(...) vectors). If there are invalid entries, add error handling with tryCatch() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:32:38