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)
}