1
在標準函數編程中,Map
取l
和函數F
,並返回一個新列表,其中F
應用於每個元素。例如,考慮:R數據幀上的高階函數映射
F(x) = x^2 and the list l = [1, 2, 3, 4, 5]
Map(f, l)
會產生清單:[1, 4, 9, 16, 25]
我想用的Map
這個概念在R數據框。我想我的功能F(x)
計算x/rowSum(row that x belongs to in the dataframe).
考慮給出的數據幀:
df <- data.frame()
for(i in 1:5)
{
df <- rbind(df, c(i, i+1, i+2, i+3, i+4))
}
colnames(df) <- c("a", "b", "c", "d", "e")
其中給出:
a b c d e
1 1 2 3 4 5
2 2 3 4 5 6
3 3 4 5 6 7
4 4 5 6 7 8
5 5 6 7 8 9
我想Map(F, df)
生產:
[,1] [,2] [,3] [,4] [,5]
v1 0.06666667 0.1333333 0.2 0.2666667 0.3333333
v2 0.10000000 0.1500000 0.2 0.2500000 0.3000000
v3 0.12000000 0.1600000 0.2 0.2400000 0.2800000
v4 0.13333333 0.1666667 0.2 0.2333333 0.2666667
v5 0.14285714 0.1714286 0.2 0.2285714 0.2571429
這是一個數據幀,其中F
適用於的每個條目df
。
唯一困難的部分是搞清楚如何寫F:
F <- function(x) x/rowSum(row in which x belongs to in dataframe)
Map(F, df)
- 我怎樣寫
F
編輯這裏是一個迭代的解決方案:
pStat <- data.frame()
for(i in 1: 5)
{
v <- df[i,]/rowSums(df[i,])
pStates <- rbind(pStates, v)
}