首页 > 解决方案 > 如何使用 for 循环附加列表?

问题描述

我在编写一个通过在另一个列表上应用 for 循环来输出列表的函数时遇到问题。我想将每个值除以列表的最大值,然后乘以 100。

这是我尝试过的和我的数据:

bn<- function(x)
{result<- list()
 p<- max(x)
for (i in 1:NROW(x))
{c <- x[i]/p*100
result[[i]] <- c
}}

其中 x 是列表输入。

df<-structure(list(tt = c("a", "b", "c", "d"), pp = c(34, 35, 77, 23)), class = "data.frame", row.names = c(NA, -4L))

在函数之外,这种方法有效,但由于某种原因,我不能让它在这里工作。任何帮助深表感谢。

标签: rfunctionloops

解决方案


尝试对您的功能进行此更改:

#Function
bn<- function(x)
{
  result<- list()
  p<- max(x)
  for (i in 1:NROW(x))
  {
    c <- x[i]/p*100
    result[[i]] <- c
  }
  return(result)
}
#Apply
bn(df$pp)

输出:

bn(df$pp)
[[1]]
[1] 44.15584

[[2]]
[1] 45.45455

[[3]]
[1] 100

[[4]]
[1] 29.87013

推荐阅读