将列中的特定值除以1000

问题描述

我需要将一列中的某些值除以1000,但不知道如何处理

我最初尝试使用此功能

test <- Updins(weight,)

test$weight <- as.numeric(test$weight) / 1000

head(test)

,以Updins为数据帧,以weight作为该列,只是为了查看它是否至少将整个列除以1000,但没有运气。它没有将“测试”识别为变量。

任何人都可以提供任何指导吗?我对R很陌生:)

解决方法

如果'Updins是数据集对象名称,我们可以选择带有[而不是(的列,因为(用于函数调用

test <- Updins['weight']
test$weight <- as.numeric(test$weight) / 1000
,

这是一个伪造的数据集,用于将所有行除以1000。我还包括一个for循环,作为仅对某些行执行此操作的一种可能方式。由于您没有指定操作方式,因此我只对值大于1,005的行执行此操作,并且我做了第二个版本,如果ID为奇数,则只能除以1,000。如果您有NA,则可能需要添加if语句来处理它们。在第三个/最后一个for循环示例中,我将提供一个示例。

ID<-1:10
grams<-1000:1009

df<-data.frame(ID,grams)

df$kg<-as.numeric(df$grams)/1000
df[,"kg"]<-as.numeric(df[,"grams"])/1000 #will do the same thing as the line above

for(i in 1:nrow(df)){
  if(df[i,"grams"]>1005){df[i,"kg3"]<-as.numeric(df[i,"grams"])/1000}
}#if the weight is greater than 1,005 grams.

for(i in 1:nrow(df)){
  if(df[i,"ID"] %in% seq(1,101,by = 2)){df[i,"kg4"]<-as.numeric(df[i,"grams"])/1000}
}#if the id is an odd number



df[3,"grams"]<-NA#add an NA to the weight data to test the next loop
for(i in 1:nrow(df)){
  if(is.na(df[i,"grams"]) & (df[i,by = 2))){df[i,"kg4"]<-NA}
           else if(df[i,"grams"])/1000}
}#Same as above,but works with NAs
,

几乎没有可用的数据或预期的输出,但这是您可能会使用的骨架:

library(dplyr) #The package you'll need,for the pipes (%>% -- passes objects from one line to the next)
test <- Updins %>% #Using the dataset Updins
   mutate(weight = ifelse(as.numeric(weight) > 199,#CHANGING weight variable. #Where weight > 50...
                          as.character(as.numeric(weight)/1000),#... divide a numeric version of the weight variable by 1000,but keep as a character... 
                          weight) #OTHERWISE,keep the weight variable as is
head(test)

我将新值保留为字符,因为您的weight变量似乎是基于您收到的某些警告('NAs introduced by coercion')的字符变量。