反转列中的值
Reversing values in a column
我的数据是这样的。我想反转 B 列的值。
df <- data.frame(A = c( "Not at all" ,"Several days" , "More than half the days", "Nearly every day "),
B = c(1, 2, 3, 4))
所以,我想要这样。
df <- data.frame(A = c( "Not at all" ,"Several days" , "More than half the days", "Nearly every day "),
B = c(4, 3, 2, 1))
rev 不适用于我的数据,数据结构为:
'data.frame': 511 obs. of 6 variables:
$ id...1 : int 1 2 3 4 5 6 7 8 9 10 ...
$ Q3.2_1...2 : num 1 3 2 2 2 2 2 2 3 2 ...
$ id...3 : int 1 2 3 4 5 6 7 8 9 10 ...
$ Q3.2_1...4 : chr "Several days" "Not at all" "Not at all" "Nearly every day" ...
$ newcolumn.id : int 1 2 3 4 5 6 7 8 9 10 ...
$ newcolumn.Q3.2_1: chr "Several days" "Not at all" "Not at all" "Nearly every day"
我要倒Q3.2_1 num.
试试这个:
#Code
df$B <- rev(df$B)
输出:
df
A B
1 Not at all 4
2 Several days 3
3 More than half the days 2
4 Nearly every day 1
或 dplyr
:
library(dplyr)
#Code
df <- df %>% mutate(B=rev(B))
我的数据是这样的。我想反转 B 列的值。
df <- data.frame(A = c( "Not at all" ,"Several days" , "More than half the days", "Nearly every day "),
B = c(1, 2, 3, 4))
所以,我想要这样。
df <- data.frame(A = c( "Not at all" ,"Several days" , "More than half the days", "Nearly every day "),
B = c(4, 3, 2, 1))
rev 不适用于我的数据,数据结构为:
'data.frame': 511 obs. of 6 variables:
$ id...1 : int 1 2 3 4 5 6 7 8 9 10 ...
$ Q3.2_1...2 : num 1 3 2 2 2 2 2 2 3 2 ...
$ id...3 : int 1 2 3 4 5 6 7 8 9 10 ...
$ Q3.2_1...4 : chr "Several days" "Not at all" "Not at all" "Nearly every day" ...
$ newcolumn.id : int 1 2 3 4 5 6 7 8 9 10 ...
$ newcolumn.Q3.2_1: chr "Several days" "Not at all" "Not at all" "Nearly every day"
我要倒Q3.2_1 num.
试试这个:
#Code
df$B <- rev(df$B)
输出:
df
A B
1 Not at all 4
2 Several days 3
3 More than half the days 2
4 Nearly every day 1
或 dplyr
:
library(dplyr)
#Code
df <- df %>% mutate(B=rev(B))