I would like to run this code in a generalised way. I have TN type variables in columns from 12 to 25 in my df. I would like to keep all my data and calculate the sum of the valid chr type of values of TN type variables by rows in a new variable called sumTN. Where the data is missing in these variables I have NA.
df$sumTN <- as.vector(rowSums(!is.na(df[, c(12:25)])))
I would like to have this code for other datasets where the TN type variables (which I would like to get a sum of them by rows) could be in different columns with different ranges.
I tried two different ways to get this but both cases I received a message that "'x' must be an array of at least two dimensions". I understand why but I cannot figure out then how I could solve this problem. Here are the codes that I tried:
firstcol = which(colnames(df)=="TN_1")
lastcol = which(colnames(df)=="TN_14")
df$sumTN <- as.vector(rowSums(!is.na(df[, c(firstcol:lastcol)])))
df$sumTN <- as.vector(rowSums(!is.na(df[, c(grep("^TN_[0-9]+$", colnames(df)))])))
Any solution would be appreciated, thanks.