当前位置: 动力学知识库 > 问答 > 编程问答 >

formatting - 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!

网友答案:

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)
网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: