简体   繁体   中英

transform dataframe column to vector(character) in R

I am newbee to R.

The code I'm working with is a bit more detailed, but I've tried to code a reproducible example here which captures all the key bits: a data frame ,for example:

   df=  x y    z
    1  1  2   cat
    2  1  3   dog
    3  1  4   pig

I want to transform df[3] to

pet<-c("cats","dogs","pigs")

then

 tt<-list()
for (animal in pet) { tt[1]<-paste("animal","is so cute!",sep="")

I want to get :

tt[1]
"cats is so cute!"
tt[2]
"dogs is so cute!"
……

Thanks for your any comments.

One nice feature of R is that you do not need to explicitly use loops, as many operations treat this implicitly. this works:

tt <- paste(df$z,'is...')

because df$z is a vector, and paste takes a vector as an input. You can see that the output of paste is a vector of strings:

str(tt)
chr [1:3] "cat is..." "dog is..." "pig is..."

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