根据R中其他列的类别添加计数器列

时间:2016-06-16 12:47:15

标签: r

我正在尝试根据两个分类值的组合向我的数据框添加一个计数器列。 e.g:

dat <- data.frame(cat1 = c("a", "a", "a", "a", "a", "b", "b", "b", "b"), 
              cat2 = c("x", "x", "x", "y", "y", "j", "j", "k", "l"), 
              Result = c(1, 1, 1, 2, 2, 1, 1, 2, 3))

我用过这个:

dat$Result <- ave(dat$cat1, dat$cat2, FUN=function(x) match(x,sort(unique(x))))

但我有错误。我在其他线程中检查了类似的建议,但答案仅适用于数字列。有人可以给我一个建议吗?谢谢你。

2 个答案:

答案 0 :(得分:2)

我们可以使用

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 42
        versionName "0.42"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services-vision:9.0.2'
    compile 'ch.acra:acra:4.7.0'
    compile 'com.android.support:support-v4:24.0.0'
    compile 'com.android.support:recyclerview-v7:24.0.0'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:design:24.0.0'
    compile 'com.android.support:support-v13:24.0.0'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
}

如果with(dat, as.numeric(ave(as.character(cat2), cat1, FUN = function(x) match(x, unique(x))))) 级别对于&#39; cat2&#39;已经处于相同的顺序,那么也可以强制执行factor

numeric

更新

使用新数据集

with(dat, ave(as.numeric(cat2), cat1, FUN = function(x) match(x, unique(x))))

答案 1 :(得分:1)

您可以使用rleid中的data.table

library(data.table)
setDT(dat)[, Result := rleid(cat2), by = cat1]
dat
#   cat1 cat2 Result
#1:    a    x      1
#2:    a    x      1
#3:    a    x      1
#4:    a    y      2
#5:    a    y      2
#6:    b    j      1
#7:    b    j      1
#8:    b    k      2
#9:    b    l      3