将 Python 数据帧操作代码转换为 R

问题描述 投票:0回答:1

我在 Python 中有一个数据帧操作,我正在尝试将其转换为 R。但是,我在 R 翻译方面遇到了问题。

col_names = China_2.columns
provinces = col_names[0]
days = col_names[1:]
day_1 = days[0]
other_days = days[1:]
China_dc = pd.DataFrame()
China_dc['Province'] = China_2[provinces]
China_dc[day_1] = China_2[day_1]
China_dc[other_days] = daily_cases
China_dc.head(3)

我尝试在 R 中将其重写为:

col_names <- names(china_2)
provinces <- col_names[1]
days <- col_names[-1]
day_1 <- days[2]
other_days <- days[-1] 
China_dc <- data.frame(Province = rep(NA_character_, nrow(China_2)))
China_dc$Province <- China_2[[provinces]]
China_dc[[day_1]] <- China_2[[day_1]]
China_dc[, other_days] <- daily_cases_df
head(China_dc, 3)

我收到 R 代码错误。具体来说,问题出在日子<- col_names[-1] line. The output I want to achieve in R should look like this (using the Python code's output for reference):

任何将 Python 代码正确翻译为 R 的帮助将不胜感激!

python r pandas data-analysis data-mining
1个回答
0
投票

由于行数的原因,您在 R 代码中遇到了问题 <- col_names[-1]. In Python, you used col_names[1:] to exclude the first element, but in R, the indexing starts at 1. So, to exclude the first element in R, you should use col_names[-1]. However, you also need to adjust the index for day_1 and other_days since R's indexing starts at 1.

更新了 R 代码:

col_names <- names(china_2)
provinces <- col_names[1]
days <- col_names[-1]
day_1 <- days[1]  # To align with R's 1-based indexing
other_days <- days[-1]  # To align with R's 1-based indexing
China_dc <- data.frame(Province = rep(NA_character_, nrow(china_2)))
China_dc$Province <- china_2[[provinces]]
China_dc[[day_1]] <- china_2[[day_1]]
China_dc[, other_days] <- daily_cases_df
head(China_dc, 3)
© www.soinside.com 2019 - 2024. All rights reserved.