r - 如何使用 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))
在函数之外,这种方法有效,但由于某种原因,我不能让它在这里工作。任何帮助深表感谢。
解决方案
尝试对您的功能进行此更改:
#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
推荐阅读
- c# - 在具有特定属性的 ObservableCollection 中搜索多个对象
- node.js - 订购 app.use() 函数的最安全和最有效的方法是什么?
- json - 使用来自 mediainfo AWS Lambda 的请求发送 json 时出现属性错误
- php - 在 Laravel 中对游标语句的原始查询
- dart - Dart 通过带有类名的字符串创建类实例
- ios - iOS UI 测试以调整 SwiftUI 应用程序上的选择器值
- arrays - 使用指针和数组索引将一个数组复制到另一个数组
- python-3.x - 如何安全地从 float64 圆形和钳位到 int64?
- php - 达到均值、中值和众数时 PHP 崩溃
- c++ - 在代码末尾注释掉 cin 会更改先前使用的 cout 语句的输出。为什么会这样?