0

我的数据框如下所示:

Location Data           Value    Value_kind
A        species1        11          single
A        species2        10          mean
A        species3        8           single
A        latitude        5.016
A        longitude       47.716
A        plot            1
B        species1        8           single
B        species2        9           single
B        species3        7           mean
B        latitude        3.203
B        longitude       40.563         
B        plot            2

我只想过滤single value_kinds并将数据重塑为:

Location   species1 species2 species3  latitude  longitude
 A             11      -       8        5.016     47.716
 B              8      9       -        3.203     40.563
4

2 回答 2

3

假设这些数据:

Lines <- "Location Data           Value    Value_kind
A        species1        11          single
A        species2        10          mean
A        species3        8           single
A        latitude        5.016
A        longitude       47.716
A        plot            1
B        species1        8           single
B        species2        9           single
B        species3        7           mean
B        latitude        3.203
B        longitude       40.563         
B        plot            2
"
DF <- read.table(text = Lines, header = TRUE, fill = TRUE)

试试这个:

library(reshape2)

DF.single <- subset(DF, Value_kind == "single" | Data == "latitude" | Data == "longitude")
dcast(DF.single, Location ~ Data, value.var = "Value")

最后一行给出:

  Location latitude longitude species1 species2 species3
1        A    5.016    47.716       11       NA        8
2        B    3.203    40.563        8        9       NA
于 2013-05-20T16:27:07.070 回答
1

假设您的真实数据看起来像您的示例数据,即每个位置的行顺序相同并且都存在,您可以执行以下操作:

library(data.table)
dt = data.table(df)

dt[Value_kind == "mean", Value := NA][,
   as.list(setattr(Value, 'names', Data)), by = Location]
#   Location species1 species2 species3 latitude longitude plot
#1:        A       11       NA        8    5.016    47.716    1
#2:        B        8        9       NA    3.203    40.563    2

as.character(Data)如果您使用因子而不是字符串,请使用)

于 2013-05-20T16:20:49.513 回答