我需要帮助按名称访问 tibble 中的值

I need help accessing a value in a tibble by name

由于源数据的动态特性,我需要按名称而不是按位置使用 count() 中的值。

我正在尝试根据现有的 ip 分配状态估算重新分配设备的人工成本。

示例: 处于活动状态的设备将是 $40.00 状态为 ActiveReservation 的设备将是 $100.00

对于下面的第一个例子: 6,323 * 10 美元 对于下面的第二个例子: 9 * 10 美元

我可以通过

得到它们
temp_dhcp_count$quantity[1] * 10

但是我不能保证 [1] 是位置并且总是“活跃”,我需要能够用名称“活跃”来称呼它

我的假设是,如果我可以将它们提取为值,我可以:

> Active = 6323
> Active * 10
[1] 63230

temp_dhcp_count$quantity[1] * 10

例如:

> temp_dhcp_count
# A tibble: 5 x 2
# Groups:   AddressState [5]
  AddressState        quantity
  <chr>                  <int>
1 Active                  6323
2 ActiveReservation       1222
3 Declined                  10
4 Expired                   12
5 InactiveReservation      287

> temp_dhcp_count$quantity[1]
[1] 6323

> temp_dhcp_count
# A tibble: 3 x 2
# Groups:   AddressState [3]
  AddressState        quantity
  <chr>                  <int>
1 Active                     9
2 ActiveReservation         46
3 InactiveReservation      642

> temp_dhcp_count$quantity[1]
[1] 9

我试过询问如何从 tibble 中提取行作为键值对,现在我试图根据反馈以这种方式询问。 How do you change the output of count from a tibble to Name Value pairs?

源数据是我导入的tsv,select基于子网,按州统计。

library(tidyverse)
library(ipaddress)
dhcp <- read_delim("dhcpmerge.tsv.txt", 
                   delim = "\t", escape_double = FALSE, 
                   trim_ws = TRUE)

dhcp <- distinct(dhcp)

network_in_review = "10.75.0.0/16"

temp_dhcp <- dhcp %>%
  select(IPAddress, AddressState, HostName) %>%
  filter(is_within(ip_address(IPAddress), ip_network(network_in_review)))

temp_dhcp %>% 
  group_by(AddressState) %>% 
  count(name = "quantity") -> temp_dhcp_count

temp_dhcp_count

经过更多挖掘,

deframe() %>% as.list()

同样适用。

您可以创建命名列表。附样本数据

temp_dhcp_count <- read.table(text="
AddressState        quantity
Active                  6323
ActiveReservation       1222
Declined                  10
Expired                   12
InactiveReservation      287", header=TRUE)

您可以创建一个命名的值列表以按名称提取它们

vals <- with(temp_dhcp_count, setNames(as.list(quantity), AddressState))
vals$Active
# [1] 6323
vals$Declined
# [1] 10

如果 vals$ 部分困扰您,您可以再次使用 with()

with(vals, {
   Active * 10 - Declined * 2
})
# [1] 63210

如果我理解目标,您可以制作一个 table 价格,然后根据需要将其合并到 temp_dhcp_count

library(tidyverse)

prices <- tribble(
  ~ AddressState, ~ price,
  "Active", 40,
  "ActiveReservation", 100,
  "Declined", 50,
  "Expired", 50,
  "InactiveReservation", 120
)

temp_dhcp_count %>% 
  left_join(prices) %>% 
  mutate(total = quantity * price)

# # A tibble: 5 x 4
# AddressState        quantity price  total
# <chr>                  <dbl> <dbl>  <dbl>
# 1 Active                  6323    40 252920
# 2 ActiveReservation       1222   100 122200
# 3 Declined                  10    50    500
# 4 Expired                   12    50    600
# 5 InactiveReservation      287   120  34440

无论 AddressStatetemp_dhcp_count 中的顺序如何,这都有效。