我有一个数据框df
col1 col2 col3 col4 col5
row1 0.0 0.0 0.0 0.0 0.0
row2 0.0 0.4 0.4 0.0 0.0
row3 0.5 1.2 0.4 0.3 0.8
row4 3.3 1.4 1.4 1.0 6.3
row5 0.0 0.2 0.0 0.0 0.0
row6 0.8 0.0 0.0 0.0 0.2
和数据框mapping
rowname mapped_name
row1 a
row2 a
row3 a
row5 b
row6 c
我希望得到
col1 col2 col3 col4 col5 mapped_name
row1 0.0 0.0 0.0 0.0 0.0 a
row2 0.0 0.4 0.4 0.0 0.0 a
row3 0.5 1.2 0.4 0.3 0.8 a
row4 3.3 1.4 1.4 1.0 6.3 NA
row5 0.0 0.2 0.0 0.0 0.0 b
row6 0.8 0.0 0.0 0.0 0.2 c
因为当我df$mapped_name <- df[mapping$rowname == rownames(df),]$mapped_name
character(0)
Warning message:
In mapping$rowname == rownames(df) :
longer object length is not a multiple of shorter object length
时,它们的长度不同。
# app/models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :teams, dependent: :destroy
end
答案 0 :(得分:1)
我们可以match
'df'的行名称和'mapping'数据集的'rowname'列,使用该数字索引来获取相应的'mapped_name'
df$mapped_name <- mapping$mapped_name[match(row.names(df), mapping$rowname)]
df
# col1 col2 col3 col4 col5 mapped_name
#row1 0.0 0.0 0.0 0.0 0.0 a
#row2 0.0 0.4 0.4 0.0 0.0 a
#row3 0.5 1.2 0.4 0.3 0.8 a
#row4 3.3 1.4 1.4 1.0 6.3 <NA>
#row5 0.0 0.2 0.0 0.0 0.0 b
#row6 0.8 0.0 0.0 0.0 0.2 c