我试图找到一种方法,使用管道从数据框中的两列(一个值,一个名称)创建一个命名向量。到目前为止,我有以下内容(使用 <form >
<br>
<input type="name" id="name" size="40" placeholder="Name" class="form-control" required><br>
<br>
<input type="email" id="email" size="40" placeholder="your email here...." class="form-control" onblur="ValidateEmail(this)" required><br>
<br>
<input type="text" id="comment" size="50" placeholder="Comment..." class="form-control" required><br><br>
<button type="submit" value="send me"class="btn" onclick="abc();">Send me</button>
</form>
作为示例数据)...
mtcars
当涉及到我的实际数据时,这不是很方便,因为我想避免将转换后的数据框的副本保存为仅使用library(tidyverse)
x <- mtcars %>%
rownames_to_column("car") %>%
select(car, mpg)
pull(mpg)
names(x) <- row.names(mtcars)
x
# Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
# 21.0 21.0 22.8 21.4 18.7
# Valiant Duster 360 Merc 240D Merc 230 Merc 280
# 18.1 14.3 24.4 22.8 19.2
# Merc 280C Merc 450SE Merc 450SL Merc 450SLC Cadillac Fleetwood
# 17.8 16.4 17.3 15.2 10.4
# Lincoln Continental Chrysler Imperial Fiat 128 Honda Civic Toyota Corolla
# 10.4 14.7 32.4 30.4 33.9
# Toyota Corona Dodge Challenger AMC Javelin Camaro Z28 Pontiac Firebird
# 21.5 15.5 15.2 13.3 19.2
# Fiat X1-9 Porsche 914-2 Lotus Europa Ford Pantera L Ferrari Dino
# 27.3 26.0 30.4 15.8 19.7
# Maserati Bora Volvo 142E
# 15.0 21.4
函数的名称列。
答案 0 :(得分:6)
我们可以使用names<-
来获取名为vector
library(tidyverse)
mtcars %>%
rownames_to_column("car") %>%
{'names<-'(.$mpg, .$car)}
或set_names
mtcars %>%
rownames_to_column("car") %>%
select(x = mpg, nm = car) %>%
pmap(set_names) %>%
unlist
答案 1 :(得分:4)
自tibble
1.3.0(2017-04-02)起,您可以使用tibble::deframe()
:
library(tidyverse)
mtcars %>%
rownames_to_column("car") %>%
select(car, mpg) %>%
deframe()
Mazda RX4 Mazda RX4 Wag Datsun 710
21,0 21,0 22,8
Hornet 4 Drive Hornet Sportabout Valiant
21,4 18,7 18,1
Duster 360 Merc 240D Merc 230
14,3 24,4 22,8
Merc 280 Merc 280C Merc 450SE
19,2 17,8 16,4
Merc 450SL Merc 450SLC Cadillac Fleetwood
17,3 15,2 10,4
Lincoln Continental Chrysler Imperial Fiat 128
10,4 14,7 32,4
Honda Civic Toyota Corolla Toyota Corona
30,4 33,9 21,5
Dodge Challenger AMC Javelin Camaro Z28
15,5 15,2 13,3
Pontiac Firebird Fiat X1-9 Porsche 914-2
19,2 27,3 26,0
Lotus Europa Ford Pantera L Ferrari Dino
30,4 15,8 19,7
Maserati Bora Volvo 142E
15,0 21,4