Nina W.
Nina W.

Reputation: 13

How to divide a column into two columns in r

I have a data frame like this:

  v1  v2 v3
1  A ddd  5
2  A ddd  7
3  B ccc  8
4  B ccc  8
5  C aaa  9
6  C aaa 11

But I want it to be like that:

  v1  v2   v3.1   v3.2
1  A   ddd    5      7
2  B   ccc    8      8
3  C   aaa    9     11

Thanks for your help!

Upvotes: 0

Views: 116

Answers (3)

milan
milan

Reputation: 4970

This will only work if your data is sorted by V2 and each value for V2 is repeated the same number of times (2 here).

cbind(df[seq(1, nrow(df), by=2),], df[seq(2, (nrow(df)), by=2),])[,c(4,5)*-1]

  v1  v2 v3 v3.1
1  A ddd  5    7
3  B ccc  8    8
5  C aaa  9   11

Upvotes: 0

phiver
phiver

Reputation: 23598

You could use something like this using dplyr and tidyr:

library(tidyr)
library(dplyr)

df1 %>% 
  group_by(v1) %>% 
  mutate(new = paste("v3", row_number(), sep = ".")) %>% 
  spread(new, v3)

# A tibble: 3 x 4
# Groups:   v1 [3]
  v1    v2     v3.1  v3.2
  <chr> <chr> <int> <int>
1 A     ddd       5     7
2 B     ccc       8     8
3 C     aaa       9    11

data:

df1 <- structure(list(v1 = c("A", "A", "B", "B", "C", "C"), v2 = c("ddd", 
"ddd", "ccc", "ccc", "aaa", "aaa"), v3 = c(5L, 7L, 8L, 8L, 9L, 
11L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6"))

Upvotes: 3

Lennyy
Lennyy

Reputation: 6132

dfnew <- aggregate(v3 ~ v1 + v2, df, I)
dfnew[order(dfnew$v1),]
  v1  v2 v3.1 v3.2
3  A ddd    5    7
2  B ccc    8    8
1  C aaa    9   11


df <- read.table(text = "
v1  v2 v3
1  A ddd  5
                 2  A ddd  7
                 3  B ccc  8
                 4  B ccc  8
                 5  C aaa  9
                 6  C aaa 11", h = T)

Upvotes: 4

Related Questions