简体   繁体   中英

How to convert selected rows into a column in R?

I have been working with a dataset which requires me to split certain selected rows and convert them into columns. The spread function which I normally use for these kind of things didn't exactly work the way I wanted. This is closest reproducible example that I have got:

df<-data.frame(person=c("Matt","Tom","Shane","Shane"),salary=c(100,200,500,400))
> df
  person salary
1   Matt    100
2    Tom    200
3  Shane    500
4  Shane    400

Suppose this is the Data Frame that I have got, how do I split the rows where person == Shane into a seperate column? This is what I have been trying to achieve:

  person salary  Shane
1   Matt    100  500
2   Tom     200  400

How do I go about doing this. Thanks a lot in advance.

I am unsure why you would want to do this, but using dplyr:

df2<-filter(df,person!='Shane')
df2$Shane<-filter(df,person=='Shane')$salary
> df2
  person salary Shane
1   Matt    100   500
2    Tom    200   400

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