I have a data.frame with several columns with either 1 number (X0 1-5), or 2 numbers (X0 6)
> head(score)
X0 X1 X2 X3 X4
1 8 <NA> <NA> <NA> <NA>
2 3 <NA> <NA> <NA> <NA>
3 <NA> 6 6 <NA> <NA>
4 6 <NA> <NA> <NA> <NA>
5 8 <NA> <NA> <NA> <NA>
6 3 4 <NA> <NA> <NA> <NA> <--- Note X0 has 2 numbers (3, 4) as characters
Split each XN column and create a YN column that is the sum of the split XN
> score$Y0 <- sapply(strsplit(as.character(score$X0), split = " "), function(x) as.numeric(x[1]) + as.numeric(x[2]))
Where XN had no split value (i.e. it was only 1 number), replace YN with XN
> score$Y0 = with(df, ifelse(is.na(score$Y0), score$X0, score$Y0))
So the final variable YN (Y0) will be either X0, or the sum of X0 splits
> head(score)
X0 X1 X2 X3 X4 Y0
1 8 <NA> <NA> <NA> <NA> 8
2 3 <NA> <NA> <NA> <NA> 3
3 <NA> 6 6 <NA> <NA> <NA>
4 6 <NA> <NA> <NA> <NA> 6
5 8 <NA> <NA> <NA> <NA> 8
6 3 4 <NA> <NA> <NA> <NA> 7 <- sum of X0 numbers (3,4)
I am able to do this manually, however if I try to wrap this into function to run Y0:X0, Y1:X1, Y2:X2, etc. I get an error message "NAs introduced by coercion".
for (i in 0:4) {
yvar = paste("score$Y",i,sep="")
xvar = paste("score$X",i,"sep="")
yvar <- sapply(strsplit(xvar,split=" "), function(x) as.numeric(x[1]) + as.numeric(x[2]))
yvar <- with(score, ifelse(is.na(yvar), xvar, yvar))
}
Warning messages:
1: In FUN(X[[1L]], ...) : NAs introduced by coercion
2: In FUN(X[[1L]], ...) : NAs introduced by coercion
3: In FUN(X[[1L]], ...) : NAs introduced by coercion
4: In FUN(X[[1L]], ...) : NAs introduced by coercion
5: In FUN(X[[1L]], ...) : NAs introduced by coercion
I have many different ways - it will work if I do them one by one, but cannot get it to work as part of a function.