0

I have a data frame in R that looks like

1 3 NULL, 2 NULL 5, NULL NULL 9

I want to iterate through each row and perform and add the two numbers that are present. If there aren't two numbers present I want to throw an error. How do I refer to specific rows and cells in R? To iterate through the rows I have a for loop. Sorry not sure how to format a matrix above.

for(i in 1:nrow(df))

vacoder169
  • 17
  • 4

2 Answers2

0

If you have something with NULL you can make it a data.frame, but that will make the columns with NULL a character vector. You have to convert those to numeric, which will then introduce NA for NULL.

rowSums will then create the sum you want.

df <- read.table(text=
"
a     b     c
1     3     NULL
2     NULL  5
NULL  NULL  9
", header =T)


# make columns numeric, this will change the NULL to NA
df <- data.frame(lapply(df, as.numeric))

cbind(df, sum=rowSums(df, na.rm = T))

#    a  b  c sum
# 1  1  3 NA   4
# 2  2 NA  5   7
# 3 NA NA  9   9
MarBlo
  • 4,195
  • 1
  • 13
  • 27
0

Data:

df <- data.frame(
  v1 = c(1, 2, NA),
  v2 = c(3, NA, NA),
  v3 = c(NA, 5, 9)
)

Use rowSums:

df$sum <- rowSums(df, na.rm = T)

Result:

df
  v1 v2 v3 sum
1  1  3 NA   4
2  2 NA  5   7
3 NA NA  9   9

If you do need a for loop:

for(i in 1:nrow(df)){
  df$sum[i] <- rowSums(df[i,], na.rm = T)
}
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • This was helpful! Row sums is useful. Say I want to do a calculation that isn't as trivial. Like: I want to sum the squares of every 2 values in each row that aren't NA. How can I access each element to check if it is NA or not? – vacoder169 Jul 14 '20 at 12:24
  • That's a whole new question. I'll think about it. Please consider upvoting and/or accepting this answer first. – Chris Ruehlemann Jul 14 '20 at 12:47
  • If you can give me a clearer sense of what data you have I could more easily help you perhaps. Can you update your question including some ten rows of your dataframe? – Chris Ruehlemann Jul 14 '20 at 15:45