编码R中向量中元素的变化

时间:2016-06-26 10:30:24

标签: r vector

给定向量vec

[1] 1 1 1 1 1 0 2 0 0 0 1 1 3 0

我想要另一个矢量来编码vec中元素的变化。我希望得到这个结果:

[1] "A" "A" "A" "A" "A" "B" "C" "D" "D" "D" "E" "E" "F" "G"

如果我们到达Z,我们会从AABB,...,ZZAAABBB开始, ......等等。

2 个答案:

答案 0 :(得分:4)

我们可以使用data.table

中的library(data.table) z1[rleid(vec)] #[1] "A" "A" "A" "A" "A" "B" "C" "D" "D" "D" "E" "E" "F" "G"
z2[rleid(vec)]     
#[1] "A" "A" "A" "A" "A" "B" "C" "D" "D" "D" "E" "E" "F" "G"

或'z2'

base R

或使用 z1[cumsum(c(TRUE, diff(vec)!=0))] #[1] "A" "A" "A" "A" "A" "B" "C" "D" "D" "D" "E" "E" "F" "G" z1[inverse.rle(within.list(rle(vec), values <- seq_along(values)))]

vec <- c(1, 1, 1, 1, 1, 0, 2, 0, 0, 0, 1, 1, 3, 0)
z1 <- unlist(sapply(1:3, function(i) do.call(paste0, 
                        expand.grid(rep(list(LETTERS), i)))))
z2 <- c(sapply(1:3, function(i) do.call(paste0, replicate(i,
                                      LETTERS, simplify=FALSE))))

数据

today = datetime.date.today()
start_time = str(today - datetime.timedelta(days=7))
end_time = str(today)

campaign = Campaign(campaign_id)
params = {
    'time_range': {
        'since': start_time,
        'until': end_time,
    },
    'fields': [
        AdsInsights.Field.campaign_id,
        AdsInsights.Field.campaign_name,
        AdsInsights.Field.impressions,
        AdsInsights.Field.unique_clicks,
        AdsInsights.Field.reach    
    ],
}
insights = campaign.get_insights(params=params)        

print(insights)

答案 1 :(得分:3)

对于更大的矢量:

set.seed(007)
x = rep(1:60, sample(1:3, 60, TRUE))

正如我所知,以下内容可能会有所帮助:

with(rle(x), 
     rep(strrep(rep_len(LETTERS, length(lengths)), 
                (0:(length(lengths) - 1)) %/% length(LETTERS) + 1L), 
         lengths))
#  [1] "A"   "A"   "A"   "B"   "B"   "C"   "D"   "E"   "F"   "F"   "F"   "G"   "G"   "H"  
# [15] "H"   "H"   "I"   "J"   "J"   "K"   "L"   "M"   "M"   "M"   "N"   "O"   "O"   "P"  
# [29] "Q"   "Q"   "R"   "S"   "S"   "S"   "T"   "U"   "U"   "V"   "W"   "W"   "W"   "X"  
# [43] "X"   "X"   "Y"   "Y"   "Y"   "Z"   "AA"  "AA"  "BB"  "BB"  "CC"  "CC"  "CC"  "DD" 
# [57] "DD"  "EE"  "EE"  "EE"  "FF"  "GG"  "HH"  "II"  "II"  "JJ"  "JJ"  "JJ"  "KK"  "KK" 
# [71] "LL"  "LL"  "LL"  "MM"  "MM"  "MM"  "NN"  "NN"  "OO"  "OO"  "OO"  "PP"  "PP"  "QQ" 
# [85] "QQ"  "QQ"  "RR"  "RR"  "SS"  "SS"  "SS"  "TT"  "UU"  "VV"  "VV"  "VV"  "WW"  "WW" 
# [99] "WW"  "XX"  "XX"  "XX"  "YY"  "YY"  "ZZ"  "ZZ"  "ZZ"  "AAA" "AAA" "AAA" "BBB" "BBB"
#[113] "CCC" "CCC" "CCC" "DDD" "DDD" "EEE" "FFF" "GGG" "GGG" "HHH"