这是我在StackOverflow上的第一个问题。我将尽力使其简洁明了,如果不是,我道歉。我也是R.的新手。我已经在StackOverflow上查看了我的问题的答案。我找到了可能有用的点点滴滴,但我不确定哪种方法最适合使用,或者如何将它们放在一起使其全部工作。
我有一个这样的数据集,名为“per1”
Day Stat1 Stat2 Stat3
10 2.12 1.84 2.11
10 2.09 1.87 2.07
10 2.08 1.92 2.07
11 1.90 1.85 1.88
11 1.87 1.85 1.93
11 1.86 1.87 1.93
我想要做的是在每一天的每个“Stat”列中找到数据的最大值。换句话说,将在每列中计算最大值的行是在Day列中包含相同值的行。输出看起来像:
Day MaxStat1 MaxStat2 MaxStat3
10 2.12 1.92 2.11
11 1.87 1.87 1.93
我想创建一个循环来定义Day列中的唯一值的数量,然后使用它来定义将在每列中计算最大值的行。但我仍然坚持如何根据唯一的日期将max函数放到每列的子集行中。到目前为止我所拥有的是粗糙的,我甚至不确定它遵循适当的R规则(再次,对R来说是新的)
days <- unique(per1$Day)
stations <- per1[,1:3]
l <- length(days)
for (k in 1:l) {
curr_day <- subset(per1, per1$Day == days[k]) ##this defines the individual day
curr_stn <- stations[curr_day,] ##this is supposed to define the number of rows as the number of rows in curr_day
for(i in 1:stations) { ##loop over each column
max[i] <- max(stations[curr_day,curr_stn]) ##take the maximum for each column based on the number of rows for each curr_day
}
}
我得到了
Error in stations[curr_day, ] : subscript out of bounds
所以我认为这意味着我没有正确定义我的论点。如果有人能帮我解决这个循环的正确格式,那将是非常感谢!任何其他更清洁/更快的方法也将受到欢迎。 (我查看了“mapply”但无法弄清楚如何编写将定义Stat列的行数作为每个唯一日的行数的行的函数)
感谢您的时间。
答案 0 :(得分:2)
这是一个简单的分组计算。困难的部分已经为我们完成了。我们可以使用aggregate
。
aggregate(. ~ Day, per1, max)
# Day Stat1 Stat2 Stat3
# 1 10 2.12 1.92 2.11
# 2 11 1.90 1.87 1.93
答案 1 :(得分:1)
R的最佳部分不必制作循环!试试这个:
library(dplyr)
maxdat <- per1 %>%
group_by(Day) %>%
summarise_each(funs(max))
答案 2 :(得分:0)
使用df['Date_Resf_Comp'] = pd.to_datetime(df['Date_Compl'], format="%m/%d/%Y")
df['Curr_Rate_Date'] = pd.to_datetime(df['Curr_Date'], format="%Y-%m-%d")
df['Prev_Rate_Date'] = pd.to_datetime(df['Prev_Date'], format="%Y-%m-%d")
df['Yrs_Sinc_Rsf'] = df.apply(lambda row: (row['Curr_Rate_Date'].year - row['Date_Resf_Comp'].year), axis=1)
df.loc[df['Yrs_Sinc_Rsf'] < 0 , 'Yrs_Sinc_Rsf'] = None
df['Yrs_Since_Rsf_2'] = df.apply(lambda row: row['Yrs_Sinc_Rsf']**2 if row['Yrs_Sinc_Rsf']>=0 else None, axis=1)
df['Yrs_Since_Rsf_3'] = df.apply(lambda row: row['Yrs_Sinc_Rsf']**3 if row['Yrs_Sinc_Rsf']>=0 else None, axis=1)
df = df[["SegID", "Curr_Date", "Prev_Date", "Curr_Rate_Date", "Date_Resf_Comp", "Curr_Distress", "Curr_Rating",
"Prev_Distress", "Prev_Rating", "OFT", "Yrs_Sinc_Rsf","Yrs_Since_Rsf_2", "Yrs_Since_Rsf_3"]]
df
更新Nick的回答:
dplyr
已弃用,已替换为summarise_each()
。相关的summarise_all()
发布说明,https://github.com/tidyverse/dplyr/releases/tag/v0.7.0。
dplyr