简体   繁体   中英

Every other factor in row to new column in R

I have a quick reformatting question. I have a data frame of ~5000 factors with names and numbers such as this:

>df
1 Puppy
2 364547
3 Kitty
4 775833
5 Bunny
6 775984

And I want to transform it to look like this:

>df
1    Puppy    364547
2    Kitty    775833
3    Bunny    775984

What is the most efficient way of doing this? Thanks!

Here it is:

Creating the data frame:

df <- read.table(text=
"1 Puppy
2 364547
3 Kitty
4 775833
5 Bunny
6 775984")

Selecting what you want (explaining better, for the first column we get only the "first" elements so we have TRUE, FALSE; and for the second column we get only the "second" elements so we have FALSE, TRUE. R recycling takes care of the rest.):

df2 <- data.frame(V1=df$V2[c(TRUE, FALSE)], V2=df$V2[c(FALSE, TRUE)])

This will give you:

df2
  V1     V2
1 Puppy 364547
2 Kitty 775833
3 Bunny 775984

The most direct thing that comes to mind for me is to use a matrix . Using @carloscinelli's sample data:

matrix(df$V2, ncol = 2, byrow = TRUE)
#      [,1]    [,2]    
# [1,] "Puppy" "364547"
# [2,] "Kitty" "775833"
# [3,] "Bunny" "775984"
data.frame(matrix(df$V2, ncol = 2, byrow = TRUE))
#      X1     X2
# 1 Puppy 364547
# 2 Kitty 775833
# 3 Bunny 775984

This works, but certainly is not that efficient:

df<-c("Puppy",364547,"Kitty",775833,"Bunny",775984)

animals <- df[which(substr(df,1,1) %in% LETTERS)]
numbs <- df[which(substr(df,1,1) %in% seq(10,from=0))]

data.frame(animals,numbs)

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