简体   繁体   中英

How to loop a strplit over multiple columns in R

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM