R语言 转换数据表

2admgd59  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(101)

我想重新排列我的数据表。在示例中,我将数据排列为df,但我希望将其显示为new.df

Name <- c("a1", "a1", "a1", "a2", "a2", "a2", "a3", "a3", "a3")
Absorbance <- c(25, 15, 20, 5, 10, 15, 50, 60, 40)
Wavelength <- c("One", "Two", "Three", "One", "Two", "Three", "One", "Two", "Three")
df <- data.frame(Name, Absorbance, Wavelength)

New.name <- c("a1", "a2", "a3")
One <- c(25, 5, 50)
Two <- c(15, 10, 60)
Three <- c(20, 15, 40)

new.df <-data.frame(New.name,One, Two, Three)

字符串

ccrfmcuu

ccrfmcuu1#

你要找的是“聚合”,这可以通过一些R基函数来实现:aggregatetapplybyxtabs。示例:

> aggregate(. ~ Name + Wavelength, df, FUN=sum)
  Name Wavelength Absorbance
1   a1        One         25
2   a2        One          5
3   a3        One         50
4   a1      Three         20
5   a2      Three         15
6   a3      Three         40
7   a1        Two         15
8   a2        Two         10
9   a3        Two         60

字符串
这是一个数据框,其中列值的组合提供索引。如果你想让一个表有两个索引,你可以使用xtabs

> res <- xtabs(Absorbance ~ Name + Wavelength, df)
> res
    Wavelength
Name One Three Two
  a1  25    20  15
  a2   5    15  10
  a3  50    40  60


xtabs的结果不是data.frame,而是table,您可以直接使用行和列名进行寻址:

> res["a1", "One"]
[1] 25

相关问题