Reputation: 95
I have data frame X that looks like this. It has 4 columns and 5 rows.
name age gender class
A 12 M C1
B 10 F C2
C M C1 N/A
D F C2 N/A
E F C1 N/A
I would like to shift all data from col 2 (age) and row 3 onward by one column to right so that gender and classes align leaving the wrongly filled age data as blank . My resulting set should look like:
name age gender class
A 12 M C1
B 10 F C2
C N/A M C1
D N/A F C2
E N/A F C1
Please note: this is a situation from a very large dataset with 4 mil records and 52 cols. Any help will be much appreciated. Thanks in advance!
Upvotes: 2
Views: 3294
Reputation: 3833
> df <- data.frame("name" = LETTERS[1:5],
+ "age" = c(12, 10, "M","F","F"),
+ "gender" = c("M", "F", "C1", "C2", "C1"),
+ "class" = c("C1", "C2", NA,NA,NA))
> df
name age gender class
1 A 12 M C1
2 B 10 F C2
3 C M C1 <NA>
4 D F C2 <NA>
5 E F C1 <NA>
> df[3:nrow(df),3:ncol(df)] <- df[3:nrow(df),2:ncol(df)]
Warning message:
In `[<-.data.frame`(`*tmp*`, 3:nrow(df), 3:ncol(df), value = list( :
provided 3 variables to replace 2 variables
> df
name age gender class
1 A 12 M C1
2 B 10 F C2
3 C M M C1
4 D F F C2
5 E F F C1
> df[3:nrow(df),2] <- NA
> df
name age gender class
1 A 12 M C1
2 B 10 F C2
3 C <NA> M C1
4 D <NA> F C2
5 E <NA> F C1
Upvotes: 2
Reputation:
Like this:
nc <- ncol(dfr)
dfr[-(1:2), 3:nc] <- dfr[-(1:2), 2:(nc-1)]
dfr[-(1:2), 2] <- NA
The negative indices in the rows mean 'everything but rows 1 and 2'.
Upvotes: 6