【发布时间】:2018-08-04 03:50:40
【问题描述】:
概述
team.df 中的每一行都包含一个NBA team。 list.of.all.stars 中的每个数据框都包含多行,这些行基于与每个 NBA 球队关联的 all star players 的数量。
使用apply() 系列函数,我如何扩展team.df 中的行以增加每支球队全明星球员的数量并合并list.of.all.stars 中的列到最终输出?
我对非apply() 方法也完全持开放态度,只是想举一个例子,我希望避免编写 for 循环。
以下是我想要的输出:
# Team_Name Team_Location Player Captain
# 1 Cavaliers Cleveland, OH LeBron James TRUE
# 2 Cavaliers Cleveland, OH Kevin Love FALSE
# 3 Warriors Oakland, CA Stephen Curry TRUE
# 4 Warriors Oakland, CA Kevin Durant FALSE
# 5 Warriors Oakland, CA Klay Thompson FALSE
# 6 Warriors Oakland, CA Draymond Green FALSE
可重现的示例
# create data frame
# about team information
team.df <-
data.frame(
Team_Name = c( "Cavaliers", "Warriors" )
, Team_Location = c( "Cleveland, OH", "Oakland, CA")
, stringsAsFactors = FALSE
)
# create list about
# all stars on each team
list.of.all.stars <-
list(
data.frame(
Player = c( "LeBron James", "Kevin Love" )
, Captain = c( TRUE, FALSE )
, stringsAsFactors = FALSE
)
, data.frame(
Player = c( "Stephen Curry", "Kevin Durant"
, "Klay Thompson", "Draymond Green"
)
, Captain = c( TRUE, FALSE, FALSE, FALSE )
, stringsAsFactors = FALSE
)
)
非 apply() 系列方法
# cbind each data frame within the list.of.all.stars
# to its corresponding row in team.df
team.and.all.stars.list.of.df <-
list(
cbind(
df[ 1, ]
, list.of.all.stars[[1]]
)
, cbind(
df[ 2, ]
, list.of.all.stars[[2]]
)
)
# Warning messages:
# 1: In data.frame(..., check.names = FALSE) :
# row names were found from a short variable and have been discarded
# 2: In data.frame(..., check.names = FALSE) :
# row names were found from a short variable and have been discarded
# collapse each list
# into data frame
final.df <-
data.frame(
do.call(
what = "rbind"
, args = team.and.all.stars.list.of.df
)
, stringsAsFactors = FALSE
)
# view final output
final.df
# Team_Name Team_Location Player Captain
# 1 Cavaliers Cleveland, OH LeBron James TRUE
# 2 Cavaliers Cleveland, OH Kevin Love FALSE
# 3 Warriors Oakland, CA Stephen Curry TRUE
# 4 Warriors Oakland, CA Kevin Durant FALSE
# 5 Warriors Oakland, CA Klay Thompson FALSE
# 6 Warriors Oakland, CA Draymond Green FALSE
# end of script #
mapply() 尝试失败
# Hoping to Apply A Function
# using a data frame and
# a list of data frames
mapply.method <-
mapply(
FUN = function( x, y )
cbind.data.frame(
x
, y
, stringsAsFactors = FALSE
)
, team.df
, list.of.all.stars
)
# view results
mapply.method
# Team_Name Team_Location
# x Character,2 Character,4
# Player Character,2 Character,4
# Captain Logical,2 Logical,4
# end of script #
【问题讨论】:
-
你有使用
apply函数吗?您是否可以控制 data.frames 列表的结构? -
@SymbolixAU 我愿意,但我愿意学习新方法!
list.of.all.stars中的对象顺序与team.df中的行顺序相关联。这能回答你的问题吗?
标签: r list dataframe apply mapply