Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (50.2k points)

I am having two columns (A and B) in my data frame. In each of the rows for columns A and B, there is a string of numbers separated by commas.

Row 1, Column A - 1,2,3,4

Row 1, Colummn B - 5,6,7,8

I want to combine 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 error:

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

1 Answer

0 votes
by (107k points)

The data frame I have defined in R programming:

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

You can simply use the separate_rows() to get the 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 you can also do that in base R:

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

                     B = as.numeric(strsplit(dataset$B, ',')[[1]])), 

                     C = A + B)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...