首页 > 解决方案 > 如何将行向量添加到数据框中?

问题描述

1. 首先

我有以下数据框

weight <- c(74,85,58,80)    
height <- c(1.68,1.83,1.58,1.72)
age <- c(22,25,21,20)
names <- c("Peter","Joseph","Marie","Xavier")
sex <- c("Male","Male","Woman","Woman")
data <- data.frame(weight,height,age,names,sex)

我需要在数据框中添加一个新个体:name=“Anne”,weight=70,height=1.72 sex= Woman。我将这些值设置为向量:

Anne <- c(70,1.72,24,"Anne","Woman")

我使用 rbind 添加向量 Anne

data <- rbind(data,Anne)

但我收到了这个警告。

Warning messages:
1: In `[`<-.factor``(*tmp*, ri, value = "Ana") :
  invalid factor level, NA generated
2: In `[`<-.factor``(*tmp*, ri, value = "Mujer") :
  invalid factor level, NA generated

“Anne”和“Woman”在数据框中显示为 NA。我怎样才能解决这个问题?

2. 第二

另外,如何向数据数据框添加一个名为 HEIGHT 的列。其中,如果个人测量值超过 1.78,则其值为“高”;否则它将具有“正常”值。

感谢你的帮助

标签: rdataframeconditional-statements

解决方案


如果您将数据读取为本文末尾所示的字符,则您的尝试将起作用。

或者,您也可以这样做

data[nrow(data) + 1, ] <- Anne
data$HEIGHT <- ifelse(data$height > 1.78, "High", "Normal")
#Faster way would be
#data$HEIGHT <- c("Normal", "High")[(data$height > 1.78) + 1]

data
#  weight height age  names   sex HEIGHT
#1     74   1.68  22  Peter  Male Normal
#2     85   1.83  25 Joseph  Male   High
#3     58   1.58  21  Marie Woman Normal
#4     80   1.72  20 Xavier Woman Normal
#5     70   1.72  24   Anne Woman Normal

数据

用 读取数据stringsAsFactors = FALSE

data <- data.frame(weight,height,age,names,sex, stringsAsFactors = FALSE)

推荐阅读