如何根据另一列的条件语句将因子列添加到数据框? [英] How to add a factor column to dataframe based on a conditional statement from another column?
本文介绍了如何根据另一列的条件语句将因子列添加到数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
morstats.agri.f< - moroccostats [c(year,agVA_g,agVA_ppp_g) ]
morstats.agri.f
问题:
所以,我想根据年列的条件,向数据框中添加一个周期框架列,其中有两个条目:1991年前和1991年之后?
数据框如下所示:
year agVA_g agVA_ppp_g
1 1960 0.00 0.000000000
2 1961 0.00 0.000000000
3 1962 0.00 0.000000000
4 1963 0.00 0.000000000
5 1964 0.00 0.000000000
6 1965 -0.13 -0.160505952
7 1966 0.09 0.065780672
8 1967 0.10 0.075941092
9 1968 -0.04 -0.064963044
10 1969 0.11 0.084530984
11 1970 0.19 0.161963328
12 1971 0.12 0.097397145
13 1972 0.19 0.16 0263118
14 1973 0.20 0.172040051
15 1974 0.01 -0.012005158
16 1975 0.14 0.111609284
17 1976 -0.02 -0.044823054
18 1977 0.32 0.299092259
19 1978 0.13 0.104535675
20 1979 0.20 0.171374920
等。
解决方案
您可以使用ifelse这样
dataframe $ periodframe< ; - ifelse(dataframe $ year> 1991年,1991年后,1991年前)
I have a dataframe for which I need to add a factor column based on a conditional statement. Here is the data.
Code:
morstats.agri.f <- moroccostats[c("year","agVA_g","agVA_ppp_g")]
morstats.agri.f
Question:
So, i want to add a column "periodframe" to the dataframe that has two entries: "pre-1991" and "post-1991" based on the condition for the column "year"?
the dataframe looks like this:
year agVA_g agVA_ppp_g
1 1960 0.00 0.000000000
2 1961 0.00 0.000000000
3 1962 0.00 0.000000000
4 1963 0.00 0.000000000
5 1964 0.00 0.000000000
6 1965 -0.13 -0.160505952
7 1966 0.09 0.065780672
8 1967 0.10 0.075941092
9 1968 -0.04 -0.064963044
10 1969 0.11 0.084530984
11 1970 0.19 0.161963328
12 1971 0.12 0.097397145
13 1972 0.19 0.160263118
14 1973 0.20 0.172040051
15 1974 0.01 -0.012005158
16 1975 0.14 0.111609284
17 1976 -0.02 -0.044823054
18 1977 0.32 0.299092259
19 1978 0.13 0.104535675
20 1979 0.20 0.171374920
etc.
解决方案
you can use ifelse like this
dataframe$periodframe <- ifelse(dataframe$year > 1991,"post-1991", "pre-1991")
这篇关于如何根据另一列的条件语句将因子列添加到数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文