R:将字符串拆分为数字并将平均值作为数据框中的新列返回 [英] R: split string into numeric and return the mean as a new column in a data frame

查看:15
本文介绍了R:将字符串拆分为数字并将平均值作为数据框中的新列返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型数据框,其中的列是数字字符串,例如1、2、3、4".我想添加一个新列,它是这些数字的平均值.我已经设置了以下示例:

I have a large data frame with columns that are a character string of numbers such as "1, 2, 3, 4". I wish to add a new column that is the average of these numbers. I have set up the following example:

     set.seed(2015)
     library(dplyr)
     a<-c("1, 2, 3, 4", "2, 4, 6, 8", "3, 6, 9, 12")
     df<-data.frame(a)
     df$a <- as.character(df$a)

现在我可以使用 strsplit 拆分字符串并返回给定行的平均值,其中 [[1]] 指定第一行.

Now I can use strsplit to split the string and return the mean for a given row where the [[1]] specifies the first row.

    mean(as.numeric(strsplit((df$a), split=", ")[[1]]))
    [1] 2.5

问题是当我尝试在数据框中执行此操作并引用行号时,出现错误.

The problem is when I try to do this in a data frame and reference the row number I get an error.

    > df2<- df %>%
    +   mutate(index = row_number(),
    +          avg = mean(as.numeric(strsplit((df$a), split=", ")
    [[index]])))
    Error in strsplit((df$a), split = ", ")[[1:3]] : 
      recursive indexing failed at level 2

谁能解释这个错误以及为什么我不能使用变量进行索引?如果我用一个常量替换 index 就行了,它似乎不喜欢我在那里使用变量.

Can anyone explain this error and why I cannot index using a variable? If I replace index with a constant it works, it seems to not like me using a variable there.

非常感谢!

推荐答案

您可以使用 sapply 循环遍历 strsplit 返回的列表,处理每个列表元素:

You could use sapply to loop through the list returned by strsplit, handling each of the list elements:

sapply(strsplit((df$a), split=", "), function(x) mean(as.numeric(x)))
# [1] 2.5 5.0 7.5

这篇关于R:将字符串拆分为数字并将平均值作为数据框中的新列返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆