Home > Software design >  How to combine strings in R with the ` ` sign?
How to combine strings in R with the ` ` sign?

Time:01-09

I have an if statment, that if an argument that is passed to the function, called case, is longer than 1, then the first colname of the data frame would be the combination of the first two values of case:

  for(i in 1:length(case)){
    if (length(case) > 1){
      colnames(scores)[1] = case[[i]]   case[[i 1]]
    } else {
      colnames(scores)[1] = case  
      
    }
  }
  

the problem is with the case[[i]] case[[i 1]] part. In python, for example, if you do a b, the result would be ab. Here I don't know how to do that. All I want is that if the condition above is TRUE, the first column of scores would become case[[i]] case[[i 1]].

case is just a vector that contains strings, like this case = c('CR','PD'). Sometimes I pass it with one value, sometimes more. In my case here I want the first column of scores to be CRPD or something like that.

If I tried the code above, I get this error, and that is of course because CR and PD are strings and here this won't work like in python:

Error in case[[i]]   case[[i   1]] : 
  non-numeric argument to binary operator

CodePudding user response:

There are two issues with your code.

First, isn’t overloaded for string concatenation in R as it is in Python. Instead, use paste() (default separator = " ") or paste0() (separator = ""). e.g., paste0(case[[i]], case[[i 1]]).

Second, your for loop doesn’t make sense, and isn’t needed if I understand your goal. As written, it overwrites the first column name on each iteration, and on the last iteration, case[[i 1]] tries to access an index one greater than the total length of the vector, which by definition doesn’t exist.

Using paste0() and ditching the for loop:

if (length(case) > 1) {
  colnames(scores)[1] <- paste0(case[[1]], case[[2]])
} else {
  colnames(scores)[1] <- case
}

head(scores)

      CRPD Gender treatment Cancer_Type CD4-T-cells
Pt1     PD   male  anti-PD1    Melanoma -0.07410987
Pt10    SD female  anti-PD1    Melanoma -0.09440127
Pt101   PR female  anti-PD1    Melanoma  0.04102849
Pt103   PD female  anti-PD1    Melanoma -0.16330295
Pt106   PD   male  anti-PD1    Melanoma -0.09424782
Pt11    PD female  anti-PD1    Melanoma -0.16731441

If your goal is to concatenate all elements of case regardless of length, you can get rid of the if statement too and just do:

colnames(scores)[1] <- paste0(case, collapse = "")
  • Related