2

我在 R 中有一个像这样格式化的数据框:

数据框

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

4

2 回答 2

17
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

#from cm to mm
data$height[data$group == "B"]  <- data$height[data$group == "B"] * 10 
于 2013-11-13T22:04:15.477 回答
4

像这样的东西?

> 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
于 2013-11-13T22:03:54.850 回答