简体   繁体   中英

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?

In my data frame in R, I have two columns (A and B).

In each of the rows for column A and B there is a string of numbers separated by commas.

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

I want to add the values and create another Column C so that output looks like:

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

Since I have multiple rows I have tried writing a for loop

The code I have is:

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  

I get the following errors Error in withCallingHandlers(expr, warning = function(w) invokeRestart("muffleWarning")): (list) object cannot be coerced to type 'double'

If your dataframe is like this:

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

You can use separate_rows to get data in separate rows and add the two columns.

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

Or using base R:

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

Here are a couple of approaches.

This uses a function list_reduction from SOfun .

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

This uses cSplit from "splitstackshape":

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

Base R solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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