我想使用列表来计算每部电影的观看者的平均年龄

时间:2019-06-22 23:48:07

标签: r list dataframe

我是一个初学者,我正在尝试使用list()和数据框来计算每部电影的观看者的平均年龄。我不知道如何解决此问题,非常感谢您的帮助。

这是我到目前为止所拥有的:

fname <- c("Jake", "Anthony", "Albert", "James", "Tony")
lname <- c("Copi", "Copi", "Einstein", "Gleick", "Gleick")
age <- c(33, 40, 77, 44, 50)
movie <- c("Iron Man", "Thor", "Iron Man", "Iron Man", "Thor")
df <- data.frame(fname, lname, age, movie, stringsAsFactors = FALSE)

my.list <- list(fname, lname, age, movie)
my.list[3]

cat("\n**** Mean age ****\n")
# Calculate the mean age for people in the same movie
mean <- mean(my.list[[3]])
print(mean)

cat("\n**** People in the family by last name ****\n")
# Calculate the number of people in family with the same last name
table <- table(my.list[2])
print(table)

Output:
**** Mean age ****
[1] 48.8

**** People in the family by last name ****

    Copi Einstein   Gleick 
       2        1        2 

3 个答案:

答案 0 :(得分:3)

使用aggregate。与您的df

aggregate(age ~ movie, data=df, mean)

     movie      age
1 Iron Man 51.33333
2     Thor 45.00000

要使用您的列表,老实说,我将其取消列出。.

unlisted_df <- data.frame(age=unlist(my.list[[3]]),movie=unlist(my.list[[4]]))
aggregate(age ~ movie, data=unlisted_df, mean)

     movie      age
1 Iron Man 51.33333
2     Thor 45.00000

答案 1 :(得分:0)

不使用列表和聚合函数的一些不同方法:

#Your Dataframe initialisation
fname <- c("Jake", "Anthony", "Albert", "James", "Tony")
lname <- c("Copi", "Copi", "Einstein", "Gleick", "Gleick")
age <- c(33, 40, 77, 44, 50)
movie <- c("Iron Man", "Thor", "Iron Man", "Iron Man", "Thor")
df <- data.frame(fname, lname, age, movie, stringsAsFactors = FALSE)

#Creating a list of unique movies within the dataframe
movie_list = unique(df$movie) 
counter = 1
#A Dataframe to store Movie along with the mean actor age
mean_df = data.frame(movie = character(), average_age = numeric(), stringsAsFactors = FALSE)

#Iterate over the movies
for(movie in movie_list){
    #Locate their index in the main dataframe
    movie_index = df$movie == movie
    #Calculate the mean of "age" column within the located indexes
    average = mean(df$age[movie_index])
    #Append the movie name and the corresponding avg. age to the 'mean_df'
    mean_df[counter,] = list(movie, average)
    #A variable to access the main dataframe, row by row
    counter = counter+1
} 

print(mean_df)

答案 2 :(得分:0)

您可能还想在context中尝试updater,得到以下输出:

mean

另外使用byby(df$age, df$movie, mean) # df$movie: Iron Man # [1] 51.33333 # ----------------------------------------------------------------------------------- # df$movie: Thor # [1] 45

with

数据

round