使用ifelse将值分配给R中的新数据框列 [英] Use of ifelse to assign values to a new dataframe column in R
问题描述
我有一个时间序列数据帧,想创建一个新的数字列,其值是现有数字列的函数,并根据星期几列进行分配.
I have a time series dataframe and would like to create a new numeric column with values which are a function of an existing numeric column and which are assigned according to the day of the week column.
例如,我将需要以下代码:
For example, I would require something like the following code:
Day <- c("Mo", "Mo", "Mo", "Tu", "Tu", "We", "We", "We", "We", "Th")
Val <- c(1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000)
df <- data.frame(cbind(Day,Val))
df$Adj <- ifelse(df$Day == "Mo" || df$Day == "Tu",
as.numeric(levels(df$Val)) + 1,
as.numeric(levels(df$Val)) + 2)
返回:
Day Val Adj
1 Mo 1000 1001
2 Mo 1000 1001
3 Mo 1000 1001
4 Tu 1000 1001
5 Tu 1000 1001
6 We 1000 1002
7 We 1000 1002
8 We 1000 1002
9 We 1000 1002
10 Th 1000 1002
不幸的是,我的代码只返回Adj作为1001s列.
Unfortunately for me, my code instead returns Adj as a column of 1001s only.
Day Val Adj
1 Mo 1000 1001
2 Mo 1000 1001
3 Mo 1000 1001
4 Tu 1000 1001
5 Tu 1000 1001
6 We 1000 1001
7 We 1000 1001
8 We 1000 1001
9 We 1000 1001
10 Th 1000 1001
我已经在"We"其中之一上测试了ifelse行,就可以了...
I've tested the ifelse on one of the "We" rows and it does the trick ...
> ifelse(df$Day[6] == "Mo" || df$Day[6] == "Tu",
+ as.numeric(levels(df$Val[6])) + 1,
+ as.numeric(levels(df$Val[6])) + 2)
[1] 1002
...但是我似乎无法使它在整个列上都能正常工作,据我了解,这是ifelse函数相对于循环的if-else语句的优势之一.
... but I can't seem to get it to work on an entire column, which I had understood is one of the advantages of the ifelse function over a looped if-else statement.
我的方法基于我能找到的最相似的问题(使用if {} else {}中的),但没有任何喜悦.我在这里想念什么?
I'm basing my approach off of the most similar questions I could find (Create new column in dataframe using if {} else {} in R) but have had no joy. What am I missing here?
推荐答案
我们可以使用%in%
来检查 Day
是否具有作为 c('Mo','Tu')
,相应地在 Val
中添加1或2.
We can use %in%
to check if Day
has value as c('Mo', 'Tu')
, add 1 or 2 accordingly to Val
.
df <- transform(df, Adj = Val + ifelse(Day %in% c('Mo', 'Tu'), 1, 2))
#you can do this without `ifelse` as well.
#df <- transform(df, Adj = Val + as.integer(!Day %in% c('Mo', 'Tu')) + 1)
df
# Day Val Adj
#1 Mo 1000 1001
#2 Mo 1000 1001
#3 Mo 1000 1001
#4 Tu 1000 1001
#5 Tu 1000 1001
#6 We 1000 1002
#7 We 1000 1002
#8 We 1000 1002
#9 We 1000 1002
#10 Th 1000 1002
这篇关于使用ifelse将值分配给R中的新数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!