R按常量乘以特定的行和列

时间:2016-10-27 19:25:31

标签: r multiplying

我有以下数据:

type <- c(1:4)
year1 <- c(1:4)
year2 <- c(1:4)
year3 <- c(1:4)
data <- data.frame(type, year1, year2, year3)

我想将Year列中的底部两行乘以2。

type <- c(1:4)
year1 <- c(1, 2, 6, 8)
year2 <- c(1, 2, 6, 8)
year3 <- c(1, 2, 6, 8)
final <- data.frame(type, year1, year2, year3)

如何在不影响列的其他行的情况下执行此操作?

2 个答案:

答案 0 :(得分:2)

以下是使用package game; import java.util.Scanner; public class RouletteTester { public static void main(String[] args) { Scanner scanner = new Scanner (System.in); int Mode; System.out.println("Please choose how you'd like to play."); System.out.println("To play by Odds & Evens, enter '1'"); System.out.println("To play by Numbers, enter '2'"); System.out.println("Enter game mode here: "); Mode = scanner.nextInt(); System.out.println("You chose game mode " + Mode); Scanner in = new Scanner (System.in); System.out.print("Enter roulette number here: "); int Number = in.nextInt(); RouletteWheel One = new RouletteWheel(); One.spin(); int r = One.getwinningNumber(); System.out.println(r); if (r == Number) System.out.println("Congratulations, The" + Number + " is a winning number!"); else System.out.println("Sorry, " + Number + " is not a winning number."); if (r == 0) System.out.println("Congratulations, 0 is an automatic win!"); Scanner inn = new Scanner (System.in); System.out.println("Odds or Evens? Type '1' for odds" + " or '2' for evens: "); int Numberr = inn.nextInt(); if (Numberr == 1) System.out.println("You choose Odds."); else System.out.println("You choose Evens."); One.spin(); int winningNumber = One.getwinningNumber(); boolean n = One.OddEvenChoice(); System.out.println("The wheel landed on..."); System.out.println(winningNumber); if ((n == true) && (winningNumber % 2 == 0)) System.out.println("You Win! E"); else if ((n == false) && (winningNumber %2 == 1)) System.out.println("You Win! O"); else System.out.println("You Lose."); } } dplyr的解决方案。如果您愿意,这将允许您调整参数。

tidyr

答案 1 :(得分:1)

如果您不知道数据的长度,并且您想要将所有包含“年”的列相乘,您可以这样做:

data[(nrow(data)-1):nrow(data),]<-data[(nrow(data)-1):nrow(data),grep(pattern="year",x=names(data))]*2

  type year1 year2 year3
1    1     1     1     1
2    2     2     2     2
3    6     6     6     6
4    8     8     8     8