更改R数据框中的列值

时间:2013-11-13 21:55:40

标签: r dataframe

我在R:

中有一个格式如下的数据框

dataframe

如何调用GROUP等于B的所有HEIGHT值并更改它们?即从厘米到毫米。

2 个答案:

答案 0 :(得分:15)

data = data.frame(group = rep(c("A", "B", "C"), each = 4), height = c(259, 243, 253, 235, 23.5, 23.6, 23.5, 24.1, 235, 234, 235, 220))
data #shows your data
data$height[data$group == "B"]  <- data$height[data$group == "B"] * 10 #from cm to mm

HTH

答案 1 :(得分:3)

这样的东西?

> set.seed(1) # simulating some data
> df <- data.frame(group=rep(c("A", "B", "C"), each=4), height=sample(100:150, 12))
> df
   group height
1      A    113
2      A    118
3      A    128
4      A    143
5      B    109
6      B    141
7      B    142
8      B    129
9      C    127
10     C    102
11     C    108
12     C    107
> # changing `height` for group `B`
> ind <- df$group %in% "B"       # locating group B
> df[ind, 2] <- df[ind, 2] * 10  # changing from cm to mm
> df
   group height
1      A    113
2      A    118
3      A    128
4      A    143
5      B   1090
6      B   1410
7      B   1420
8      B   1290
9      C    127
10     C    102
11     C    108
12     C    107