Nckh
Nckh

Reputation: 67

How to append list with a for loop?

I'm having issues writing a function that outputs a list by applying a for-loop over another list. I want to divide each value by the list's maximum and then multiply by 100.

Here is what I tried and my data:

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

where x is list input.

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

Outside the function this approach works but for some reason I can't make it work here. Any help is much appreciated.

Upvotes: 1

Views: 44

Answers (1)

Duck
Duck

Reputation: 39585

Try this change on your function:

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

Output:

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

[[2]]
[1] 45.45455

[[3]]
[1] 100

[[4]]
[1] 29.87013

Upvotes: 2

Related Questions