将长格式数据转换为 R 中的三维数组
Convert Long Form data to three dimensional array in R
我有一些数据如下所示:
> ExampleData
# A tibble: 14,833 x 4
CountryCode Flow FuelType Value
<fct> <fct> <fct> <dbl>
1 ALB road coa 0
2 ALB services coa 3.3
3 ALB manufact coa 113.1
4 ALB mining coa 0
5 ALB road nga 0
6 ALB services nga 2.4
[...]
从代表国家、流量和燃料类型的每个组合的意义上讲,数据是完整的。
我想将其转换为三维数组,其中国家代表一维,流量代表另一维,燃料类型代表第三维。所以我可以引用数据 X[a,b,c],其中 a b 和 c 分别是我的因子 CountryCode、Flow 和 FuelType 的整数值。
所以我正在寻找的是 'wide' 数据的多维形式。
一个选项是 xtabs
来自 base R
out <- xtabs(Value ~ CountryCode + Flow + FuelType, data = ExampleData)
out
#, , FuelType = coa
# Flow
#CountryCode manufact mining road services
# ALB 113.1 0.0 0.0 3.3
#, , FuelType = nga
# Flow
#CountryCode manufact mining road services
# ALB 0.0 0.0 0.0 2.4
我们可以使用位置索引或键提取单个元素
out["ALB", "manufact", "coa"]
#[1] 113.1
或 tapply
tapply(ExampleData[['Value']], ExampleData[-4], FUN = I)
数据
ExampleData <- structure(list(CountryCode = c("ALB", "ALB", "ALB", "ALB", "ALB",
"ALB"), Flow = c("road", "services", "manufact", "mining", "road",
"services"), FuelType = c("coa", "coa", "coa", "coa", "nga",
"nga"), Value = c(0, 3.3, 113.1, 0, 0, 2.4)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
我有一些数据如下所示:
> ExampleData
# A tibble: 14,833 x 4
CountryCode Flow FuelType Value
<fct> <fct> <fct> <dbl>
1 ALB road coa 0
2 ALB services coa 3.3
3 ALB manufact coa 113.1
4 ALB mining coa 0
5 ALB road nga 0
6 ALB services nga 2.4
[...]
从代表国家、流量和燃料类型的每个组合的意义上讲,数据是完整的。
我想将其转换为三维数组,其中国家代表一维,流量代表另一维,燃料类型代表第三维。所以我可以引用数据 X[a,b,c],其中 a b 和 c 分别是我的因子 CountryCode、Flow 和 FuelType 的整数值。
所以我正在寻找的是 'wide' 数据的多维形式。
一个选项是 xtabs
来自 base R
out <- xtabs(Value ~ CountryCode + Flow + FuelType, data = ExampleData)
out
#, , FuelType = coa
# Flow
#CountryCode manufact mining road services
# ALB 113.1 0.0 0.0 3.3
#, , FuelType = nga
# Flow
#CountryCode manufact mining road services
# ALB 0.0 0.0 0.0 2.4
我们可以使用位置索引或键提取单个元素
out["ALB", "manufact", "coa"]
#[1] 113.1
或 tapply
tapply(ExampleData[['Value']], ExampleData[-4], FUN = I)
数据
ExampleData <- structure(list(CountryCode = c("ALB", "ALB", "ALB", "ALB", "ALB",
"ALB"), Flow = c("road", "services", "manufact", "mining", "road",
"services"), FuelType = c("coa", "coa", "coa", "coa", "nga",
"nga"), Value = c(0, 3.3, 113.1, 0, 0, 2.4)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))