在R中添加包含行元素的新列

时间:2014-12-06 17:30:57

标签: r rows multiple-columns

我有一个评级和用户表。 我想在Users表中添加一个名为" AvRating" 对于该列的每一行,我希望每个用户给出的平均评分。 我遍历评级表中的所有用户ID,并获得所有相应评级的平均值。 然而,专栏" AvRating"包含一堆N / A,这就是全部。

Ratings = read.table("Ratings.txt", 
               sep="\t", 
               col.names=c("ID", "MId", "Rating"), 
               fill=FALSE, 
               strip.white=TRUE)    


Users = read.table("Users.txt", 
               sep="\t", 
               col.names=c("ID", "Age", "Gender", "Occupation", "ZIP"), 
               fill=FALSE, 
               strip.white=TRUE) 


Users["AvRating"] <- NA   


for(i in 1:943){    # 943 rows in "Ratings" table

    N = 0
    x = i

    # Counting number of ratings by specific User

    while(Ratings[1, i]==x){

        N=N+1

    }

    x = i

    temp = rep(0, N)

    for(j in 0:N){

        temp[j] = Ratings[3, i] 

    }

    t = mean(temp)


    Users[6][i] = t

}  

Users[6]               

1 个答案:

答案 0 :(得分:1)

使用R,您几乎不需要循环。使用dplyr

# first load data and dplyr   
library(dplyr)
user.ave.rating <- Ratings %>% 
    group_by(ID) %>%
    summarize(AvRating = mean(Rating, na.rm = TRUE))
# Join this to your user table
Users <- left_join(Users, user.ave.rating)

在基础R中也很容易,但我发现聚合的语法更难以理解/记住:

user.ave.rating <- aggregate(Rating ~ ID, FUN = mean, data = Ratings, na.rm = TRUE)
names(user.ave.rating)[2] <- "AvRating"
Users <- merge(Users, user.ave.rating, by = "ID")