r - 如何将行向量添加到数据框中?
问题描述
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,则其值为“高”;否则它将具有“正常”值。
感谢你的帮助
解决方案
如果您将数据读取为本文末尾所示的字符,则您的尝试将起作用。
或者,您也可以这样做
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)
推荐阅读
- java - paintComponent 执行了两次,绘制失败
- node.js - 使用 nodejs 中的 async.js 模块为数组的每个元素处理异步
- string - 常量块中的原始字符串文字
- css - 如何合并不在 Google Material for Angular 中的图标?
- amazon-web-services - 无服务器框架 AWS 跨账户自定义授权方
- android - Google Play Install Referrer 在某些响应中缺少活动 ID
- java - 如何从 JavaFX 中的 Java 控制器控制 CSS 文件
- local-storage - 电子将旧应用程序的本地存储迁移到新应用程序
- d3.js - vega 是否只支持创建图表,不支持图表?
- python-2.7 - serialposix.py 中的“_reconfigure_port”函数在重新启动串行服务器时引发错误。使用 Pymodbus 模块