0

I have an assignment for stat computing, and now I get stuck on something you all probably think pretty easy, I won't ask you to solve the whole thing for me, however this is the problem:

I have a data frame with multiple columns I need to slip these columns into two I know how to slipt one column, in this case column three:

strsplit((my_data[,3]), split = " ")

however if I try to do this over al the column I need this for:

strsplit((my_data[,3:14]), split = " ")

I get this error: Error in strsplit((my_data[, 3:14]), split = " ") : non-character argument

So I understand I probably need a loop, however I don't know how to do this, this is what I tried:

test <- for(i in 3:ncol(my_data)){
  strsplit((my_data[i]), split = " ")
}

but yeah that doesn't work

enter code here

Good2Bi
  • 1
  • 1
  • The reason is not because of non-character column, it is only because you are splitting a `data.frame` i.e. `df1 <- data.frame(col1 = c('l l', 'a b', 'c d'), col2 = c('a c', 'd e', 'b f'), stringsAsFactors=FALSE) strsplit(df1, ' ') #Error in strsplit(df1, " ") : non-character argument` . But of course `strsplit` works on `character` column and make sure that your columns are `character` class. Here, I would use `lapply(df1, function(x) strsplit(x, ' '))` – akrun Dec 04 '16 at 14:49

1 Answers1

0

You can use apply for this job:

my_data_split = apply(my_data, 2, function(x) strsplit(x, split = " "))

This will store the results in a list. If you would like to store the results in another data type you could use one of the other apply functions.

Good luck!

PaulH
  • 181
  • 1
  • 5
  • thank you so much I used this one instead: my_data_314 <- sapply(my_data[, 3:14], strsplit, split = " "), since I noticed column 1 and 2 that did not need splitting anyway werent character values either... – Good2Bi Dec 04 '16 at 15:14
  • No I'm just trying to make column names for my_data_314[1] and [2] that include the old name and an A or B – Good2Bi Dec 04 '16 at 15:18