如何在R中的小型数据框中为新变量添加因子?

时间:2017-02-15 19:55:57

标签: r

快速提问:我有一个我融化的小数据集,现在想添加一个列变量:

> df
          taxa  spring summer     fall LocationA LocationB
1 Chironominae 1957.50 537.54 3396.765  1712.196   2958.642
2   Culicoides  863.53 343.08 2796.647  1907.804   1384.642
3     Naididae  949.88  40.75  147.569   641.911     91.566
4     Asioplax 1799.41 163.04  119.882     0.000   1343.528
5     Nematoda    0.00 166.00   27.647    53.679     45.057
6  Stilobezzia    0.00  20.38  885.961   605.179    222.321

taxa <- melt(df)

> taxa
           taxa   variable    value
1  Chironominae     spring 1957.500
2    Culicoides     spring  863.530
3      Naididae     spring  949.880 .....

如何为&#34; variable.type&#34;添加列?它定义了&#34;变量&#34;是赛季(第1:18行)还是位置(第19:30行)?我试过了:

taxa$variable.type <- c("Season"[1:18], "Location"[19:30])

但最后只有一个包含大量NA的列。

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试:

df$variable.type <- ifelse(df$variable %in% c("spring","summer","fall"),"season","location")