簡體   English   中英

如何在使用transmute_if / transmute_at的情況下實現由列划分的大標題

[英]How to achieve a large tibble divided by a column within using transmute_if / transmute_at

我有個小標題,說:

> library(tibble)
> as_tibble(iris)
# A tibble: 150 x 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
 1          5.1         3.5          1.4         0.2  setosa
 2          4.9         3.0          1.4         0.2  setosa
 3          4.7         3.2          1.3         0.2  setosa
 4          4.6         3.1          1.5         0.2  setosa
 5          5.0         3.6          1.4         0.2  setosa
 6          5.4         3.9          1.7         0.4  setosa
 7          4.6         3.4          1.4         0.3  setosa
 8          5.0         3.4          1.5         0.2  setosa
 9          4.4         2.9          1.4         0.2  setosa
10          4.9         3.1          1.5         0.1  setosa
# ... with 140 more rows

我可以使用Petal.widthPetal.width通過說Petal.width來划分每一列嗎?

就像是

> iris[,-c(5)]/iris[,4]
    Sepal.Length Sepal.Width Petal.Length Petal.Width
1      25.500000   17.500000     7.000000           1
2      24.500000   15.000000     7.000000           1
3      23.500000   16.000000     6.500000           1
4      23.000000   15.500000     7.500000           1
5      25.000000   18.000000     7.000000           1
6      13.500000    9.750000     4.250000           1
7      15.333333   11.333333     4.666667           1
8      25.000000   17.000000     7.500000           1
9      22.000000   14.500000     7.000000           1
10     49.000000   31.000000    15.000000           1
11     27.000000   18.500000     7.500000           1

但不知道確切的變量名稱,只有.Length.Width的結尾

謝謝,

我們可以使用它們中的任何一個。 區別在於,我們只想對numeric列進行轉換,那么通過避免索引或按列名, transmute_if會更合適

iris %>% 
   as_tibble %>% 
   transmute_if(is.numeric, funs(./iris$Petal.Width))

如果我們已經知道列名或索引,則可以使用transmute_at

iris %>%
   as_tibble %>%
   transmute_at(1:4, funs(./iris$Petal.Width))

如果特定於特定的列集,則在列名中說那些帶有“寬度”作為后綴部分的列

iris %>%
    as_tibble %>% 
    transmute_at(vars(ends_with("Width")), funs(./iris$Petal.Width))

如果打算同時保留其他列,請使用mutate_at

iris %>%
    as_tibble %>% 
    mutate_at(vars(ends_with("Width")), funs(./iris$Petal.Width))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM