基于其他列创建列数据集

时间:2018-02-07 09:21:14

标签: r dataframe

我有以下数据框

name                surname 
Mr. William John    Mellors
Miss. Wendla Maria  Heininen
Mrs. Sandra         Gonzalez

这取决于" name"专栏说" Mrs" "小姐" "女士"我必须为名为" title"

的新专栏分配一个或另一个值

例如对于" MS" ,是已婚男人,因为"小姐"未婚的女性,或者#34; Mrs"已婚妇女。

这是输出数据集。

 name                surname      title
Mr. William John    Mellors       married men
Miss. Wendla Maria  Heininen      not married women
Mrs. Sandra         Gonzalez      married women

我不知道是否有功能,或使用ifelse并将其分配到我的第一个数据帧。

代码无效,

#dataframe loading
titanic <- read.table("C:/Users/sergio.urrea/Downloads/titanic.csv", header = TRUE, sep = ";")

titanic$title<-ifelse(titanic$name="Master","Hombre soltero",
                    ifelse(titanic$name="Miss","Mujer soltera"))

由于

3 个答案:

答案 0 :(得分:2)

假设您的data.frame被调用&#34; df&#34;

df[grepl("^Mr.$",df$name),3] = "married men"
df[grepl("^Miss.$",df$name),3] = "not married women"
df[grepl("^Mrs.$",df$name),3] = "married women"

您还可以明确地参考第3列并保护这些&#34;。&#34;

df[grepl("^Mr\\.$",df$name),]$title = "married men"
df[grepl("^Miss\\.$",df$name),]$title = "not married women"
df[grepl("^Mrs\\.$",df$name),]$title = "married women"

答案 1 :(得分:0)

使用dplyr中的str_detect()stringr

library(dplyr)
    library(stringr)

    df = data.frame(name = c("Mr. William John", "Miss. Wendla Maria", "Mrs. Sandra"), 
                        surname  = c(" Mellors", "Heininen", "Gonzalez")) 


        df %>% mutate(title = ifelse(str_detect(name, "Mr."), "married men",
                                     ifelse(str_detect(name, "Mrs."), "married woman",  "not married woman")))

                   name  surname             title
    1   Mr. William John  Mellors       married men
    2 Miss. Wendla Maria Heininen not married woman
    3        Mrs. Sandra Gonzalez       married men

答案 2 :(得分:0)

使用ifelse方法:

extern "C" {
    static mut a: [i32; 10];
}

fn set_a(val: i32, index: usize) {
    unsafe {
        a[index] = val;
    }
}

fn get_a(index: usize) -> i32 {
    unsafe { a[index] }
}