【问题标题】:R programme, to create a new dataframe to remove some columns and rowsR程序,创建一个新的数据框来删除一些列和行
【发布时间】:2016-11-15 00:28:43
【问题描述】:

使用瑞士数据集:

  1. 我想创建一个仅包含第 10、11、13 行以及仅变量 Exam、Education 和 Infant.Mortality 的数据框。

  2. 创建一个新变量,它将是考试(考试/总)的比例

我知道如何获取/创建 FIRST/LAST 3 或 5 0r 甚至 100 但不是列或行的变量

i.e   swiss[nrows(swiss)-4:nrows,]

columns:  colnames(swiss)
[1] "Fertility"        "Agriculture"     
[3] "Examination"      "Education"       
[5] "Catholic"         "Infant.Mortality".... here i want only for examination  education & infant

【问题讨论】:

  • swiss[c(10,11,13), c("Examination", "Education","Infant.Mortality")]

标签: r


【解决方案1】:

您可以使用 c() 函数中的行号显式调用行

library(dplyr)
df_new <- df %>% select(Examination, Education, Infant) %>% mutate(new_var = Examination / Total)

df_new <- df_new[c(10,11,13),]

您的另一个选择是使用基础 R:

df_new <- df[c(10,11,13),c("Examination", "Education", "Infant")]
df_new$new_var <- df_new$Examination / df_new$Total***

*** 你必须定义总计是多少

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 2019-08-12
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多