繁体   English   中英

R:我的数据框有 2 列,每行都有一串数字,有没有办法拆分字符串并添加每列的值?

[英]R: My data frame has 2 columns that have a string of numbers in each row, is there a way to split the string and add the values of each column?

在 R 的数据框中,我有两列(A 和 B)。

在 A 列和 B 列的每一行中,都有一个用逗号分隔的数字字符串。

Row 1, Column A - 1,2,3,4      
Row 1, Column B - 5,6,7,8

我想添加值并创建另一列 C 以便 output 看起来像:

Row 1, Column C - 6,8,10,12

由于我有多行,我尝试编写一个 for 循环

我的代码是:

library(stringr)
for i in 1:nrow(dataset)
row_i = dataset[i, ]
A1 = str_split(row_i$A, ",")
B1 = str_split(row_i$B, ",")
unlist(A1)
unlist(B1)
as.numeric(A1)
as.numeric(B2)
dataset$C  = A1+B2
end  

我收到以下错误 withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning")): (list) object 不能强制输入'double'

如果你的 dataframe 是这样的:

dataset <- data.frame(A = '1,2,3,4', B = '5,6,7,8')

您可以使用separate_rows的行来获取单独行中的数据并添加两列。

library(dplyr)

dataset %>%
 tidyr::separate_rows(A, B, convert = TRUE) %>%
 mutate(C = A+B)

#  A B  C
#1 1 5  6
#2 2 6  8
#3 3 7 10
#4 4 8 12

或使用基础 R:

transform(data.frame(A = as.numeric(strsplit(dataset$A, ',')[[1]]), 
                     B = as.numeric(strsplit(dataset$B, ',')[[1]])), 
                     C = A + B)

这里有几种方法。

这使用来自SOfun 的 function list_reduction list_reduction

df <- data.frame(A = c("1,2,3,4", "9,10,11,12,13"),
                 B = c("5,6,7,8", "14,15,16,17,18"))
                 
## Grab `list_reduction` from "SOfun"
source("https://raw.githubusercontent.com/mrdwab/SOfun/master/R/list_reduction.R")

## Split the list
df_list <- lapply(df, function(x) type.convert(strsplit(as.character(x), ",", fixed = TRUE)))
df["C"] <- list_reduction(df_list, "+", flatten = TRUE)
df
#               A              B                  C
# 1       1,2,3,4        5,6,7,8       6, 8, 10, 12
# 2 9,10,11,12,13 14,15,16,17,18 23, 25, 27, 29, 31

这使用“ cSplit ”中的 cSplit:

library(splitstackshape)
library(data.table)
cSplit(as.data.table(df, keep.rownames=TRUE), c("A", "B"), ",", "long")[
  , C := A + B][, lapply(.SD, toString), "rn"]
#    rn                 A                  B                  C
# 1:  1        1, 2, 3, 4         5, 6, 7, 8       6, 8, 10, 12
# 2:  2 9, 10, 11, 12, 13 14, 15, 16, 17, 18 23, 25, 27, 29, 31

基础 R 解决方案:

paste0(rowSums(sapply(df, function(x){ 
    as.numeric(unlist(strsplit(as.character(x), ",")))
    }
  )
),
collapse = ",")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM